Write a C program (\"procs.c\") that creates three processes: a parent process t
ID: 3605396 • Letter: W
Question
Write a C program ("procs.c") that creates three processes: a parent process that creates two child processes.
The first child should do the following:
- display "First child is born, my pid is ..."
- display 100 times the message "First child executes iteration X", where X is the number of the iteration
- display "First child dies quietly."
The second child should do the following:
- display "Second child is born, my pid is ..."
- display 100 times the message "Second child executes iteration X", where X is the number of the iteration
- display "Second child dies quietly."
The parent process should do the following:
- display "Parent process is born, my pid is ..."
- create the first child
- create the second child
- wait for both children to complete their execution
- display "Parent process dies quietly."
Compile the program using gcc and name the executable "procs.out". Execute the program several times and notice how the output of the two children interlace. Files "procs.c" and "procs.out" should be posted under the Homework 2 assignment for grading.
A possible output of this program is:
nova> ./procs.out
Parent process is born, my pid is 7847
First child is born, my pid is 7848
First child executes iteration: 1
First child executes iteration: 2
First child executes iteration: 3
First child executes iteration: 4
First child executes iteration: 5
Second child is born, my pid is 7849
Second child executes iteration 1
Second child executes iteration 2
Second child executes iteration 3
First child executes iteration: 6
Second child executes iteration 4
Second child executes iteration 5
Second child executes iteration 6
First child executes iteration: 7
Second child executes iteration 7
Second child executes iteration 8
...
Second child executes iteration 100
Second child dies quietly.
First child executes iteration: 8
...
First child executes iteration: 100
First child dies quietly.
Parent process dies quietly.
Explanation / Answer
void main()
{
int ctr = 1;
printf("Parent process is born, my pid is %d ", getpid());
if(!fork())
{
printf("First child is born, my pid is %d ", getpid());
while(ctr <= 10)
{
printf("First child executes iteration: %d ", ctr);
ctr++;
}
printf("First child dies quietly ");
}
if(!fork())
{
printf("Second child is born, my pid is %d ", getpid());
while(ctr <= 10)
{
printf("Second child executes iteration: %d ", ctr);
ctr++;
}
printf("Second child dies quietly ");
exit(0);
}
wait();
printf("Parent process dies quietly ");
}
// This will do the job just include the necessary header files
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.