Parent Processes

In the below code, I ran and the output gave me

0 for Line A
26111 for Line B
26111 for Line C
26110 for Line D


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>
#include <sys/wait.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("parent: pid = %d", pid); //line C
printf("parent: pid1 = %d", pid1); //line D
wait(NULL);
}

return 0;
}



My question is what would the output be if the parent pid was 2600 and the child pid was 2603? Is there a way to use those variables in the program. JUst by looking, I would think it would produce 0, 2600, 2600, 2603. Is this right?
According to your above code,

pid will always be zero in the child and the process ID of the child in the parent.
pid1 will be the process ID of the child in the child and the process ID of the parent in the parent.
According to that, 0, 2600, 2600, 2603 would be the output if the parent is 2600 and 2603 was the child, right?
No. Read my post above again, and then look what variable each line is printing.

A prints pid in child;
B prints pid1 in child;
C prints pid in parent;
D prints pid1 in parent.
Topic archived. No new replies allowed.