I need help understanding how to get the following answers. Please note that these are review questions, not something I am trying to have done. I want to understand the concepts behind how the answers were achieved. The instructor has told us that questions similiar to these will be on our next exam.
1) Including the initial parent process, how many processes are created in the below program?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <stdio.h>
#include <unistd.h>
int main()
{
//fork a child process
fork();
//fork another child process
fork();
//and fork another
fork();
return 0;
}
|
2) Using the below program, identify the values A, B, C, and D. (assume the actual pids of the parent and child are 2600 and 2603, respectively)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
//fork a child process
pid = fork();
if (pid< 0) //error occurred
{
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) //child process
{
pid1 = getpid();
printf("child: pid = %d", pid); //line A
printf("child: pid1 = %d", pid1); //line B
}
else //parent process
{
pid1 = getpid();
printf("child: pid = %d", pid); //line C
printf("child: pid1 = %d", pid1); //line D
wait(NULL);
}
return 0;
}
|
3) Using the below program, explain what the output will be at line A
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main()
{
pid_t pid;
pid = fork()
if (pid == 0) //child process
{
value += 15;
return 0;
}
else (id pid > 0) //parent process
{
wait(NULL);
printf("Parent: value = %d", value); //Line A
return 0;
}
}
|
Please help if you can...I may be way off base here, but here is what I think:
One the first question, I am thinking either 7 or 8. Doesn't the fork() copy both a child and a parent process, thus giving 7?
On the second I believe it is:
A 0
B 2603
C 2600
D 2600
On the third, would in not simply be 5?
Thanks for any advice...I am trying hard, but I am at my wits end..