Using the program listed below, identify the values of pid at lines A, B, C, and
ID: 3905415 • Letter: U
Question
Using the program listed below, identify the values of pid at lines A, B, C, and D.
Include a screenshot of the code running.
#include <sysltypes.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 / Answer
ANSWER:
Explaination inline with code below
A - child:pid = 0 (pid as seen in child process)
B - child:pid1 = n1 ( the child process's id )
C- parent:pid = n1 (the child process's id as seen in parent)
D - parent:pid1 = n2 (the parent process id)
In above n1 is the child process's pid and n2 is the parent process's id. You can even verify the results by executing the code.
We need to note that child:pid1 will be same as parent:pid.
sample run produced the following results:(The numbers wil vary for your execution)
child: pid = 0child: pid1 = 990parent: pid = 990parent: pid1 = 989
======== Explaination ===============
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) { /* in child process pid will be 0*/
/*this block of code will be executed by the child process.
now getpid() call inside child process will set pid1 to child
process's id. */
pid1 = getpid();
printf("child: pid = %d",pid); /* A will print 0*/
printf("child: pid1 = %d",pid1); /* B will print child process's id*/
}
else { /* in parent process pid will not be 0 and will have the child process id number (non zero)
and this block will be executed by parent process */
pid1 = getpid() ; /*returns the parent's process id and set it in pid1*/
printf("parent: pid = %d",pid); /* C the child's pid*/
printf("parent: pid1 = %d" ,pid1); /* D the parent's pid*/
wait(NULL);
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.