In: Computer Science
Using the program below, identify the values of pid at lines A, B, C, and D. (Assume that the actual pids of the parent and child are 2600 and 2603, respectively.)
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
/* fork a child process */
pid = fork();
if (pid lt; 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */
pid1 = getpid();
printf("child: pid = %d",pid); /* A */
printf("child: pid1 = %d",pid1); /* B */
}
else { /* parent process */
pid1 = getpid();
printf("parent: pid = %d",pid); /* C */
printf("parent: pid1 = %d",pid1); /* D */
wait(NULL);
}
return 0;
}
Fork() function returns 0 to the child process and child process id to the parent process. getpid() function returns current process id. I included the comments in the lines of A B C D in the following code
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
/* fork a child process */
pid = fork();
if (pid lt; 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */ // since this is child code
// fork() return value will be 0
// so pid holds 0
pid1 = getpid(); // getpid() returns current process id i.e., child process id.
printf("child: pid = %d",pid); /* A */ // prints pid i.e., 0
printf("child: pid1 = %d",pid1); /* B */ // prints current process id (child process id) i.e., 2603
}
else { /* parent process */ //since this is parent code
//fork() return value will be child's process id
// so pid holds child's process id i.e.,
pid1 = getpid(); //getpid() returns current process id ie., parent process id.
printf("parent: pid = %d",pid); /* C */ // prints pid i.e., 2603
printf("parent: pid1 = %d",pid1); /* D */ // prints current process id (parent process id) i.e., 2600
wait(NULL);
}
return 0;
}