In: Computer Science
Q2) Using the program in Figure 2, 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.) Give a brief
explanation.
#include <sys/types.h> #include <sys/wait.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); /* 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; }
Figure 2 - What are the pid values displayed?
Program:
#include <sys/types.h>
#include <sys/wait.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); /* 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;
}
Explanation:
/*at line A
* pid stores return value of fork(), fork() returns 0 for
child process
* so child pid=0
*prints 0 at line A
*/
/*at line B
* pid1 stores return value of getpid(), getpid() returns
process id of process
* so child pid1 = 2603 (since given that child pid
= 2603)
*prints 2603 at line B
*/
/*at line C
* pid stores return value of fork(), fork() returns pid of
child process for parent process
* so parent pid=2603 (since given that child pid =
2603)
*prints 2603 at line C
*/
/*at line D
* pid1 stores return value of getpid(), getpid() returns
process id of process
* so parent pid1=2600 (since given that parent pid
= 2600)
*prints 2600 at line D
*/
Output: (The output is same but there won't be any new lines)
child: pid = 0
child: pid1 = 2603
parent: pid = 2603
parent: pid1 = 2600