This is an assignment for my Operating Systems course and I really need help! He
ID: 639022 • Letter: T
Question
This is an assignment for my Operating Systems course and I really need help! Here's how it works:
Written below is a C++ code for creating a child process in Linux:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
#define MAX_COUNT 200
#define PROC_COUNT 1
void ChildProcess(void)
{
for (int i=1; i < MAX_COUNT; i++)
printf(" This line is from child, pid=%d, count=%d ", getpid(), i);
printf("** Child process complete ");
}
void ParentProcess(void)
{
for (int i=1; i < MAX_COUNT; i++)
printf(" This line is from parent, pid=%d, count=%d ", getpid(), i);
printf("** Parentprocess complete ");
}
int main()
{
pid_t pid;
printf("Parent process: pid=%d ", getpid());
pid = fork();
if (pid == 0)
ChildProcess();
else
ParentProcess();
}
This is the main part that I need help with:
Using Ubuntu and Gedit, here are the steps to implement and explore:
A. Modify the program to create four child processes. Capture the output of the program (you can type ./testfork >forktestoutput to save the output). What can you see about the relative execution of the five processes?
B. Modify the program to print out any available information on the child process after the loop completes
Explanation / Answer
#include #include #include #include #include void main(int argc, char *argv[]) { int pipefd[2]; char buff[100]; int childpid; int size; FILE *file; if (argc != 2) { printf("usage: %s ", argv[0]); exit(1); } if (pipe(pipefd) < 0) { perror("can't open pipe "); } if ((childpid = fork()) == 0) { sleep(1); size = read(pipefd[0], buff, sizeof(buff)); file = fopen(buff, "r"); if (file == NULL) { write(pipefd[1], "Can't open file", 15); exit(1); } while (!feof(file)) { if (fgets(buff, sizeof(buff), file) == NULL) { write(pipefd[1], "Error reading file", 18); } else { write(pipefd[1], buff, sizeof(buff)); } } } else if (childpid > 0) { size = strlen(argv[1]); if (write(pipefd[1], argv[1], size) != size) { perror("Error writing to pipe "); } wait(NULL); while ((size = read(pipefd[0], buff, sizeof(buff))) > 0) { write(1, buff, size); } } exit(0); }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.