C programming problem 1: From the program below, identify the values of the pids
ID: 3755187 • Letter: C
Question
C programming problem
1: From the program below, identify the values of the pids at lines A, B, C, and E. (Assume that the pids of the processes are 2600, 2603, and 2675 (in creation order). Also assume that fork will always succeed.)
int main() {
pid_t pid, pid1, pid2;
pid = fork();
pid1 = getpid();
if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) {
printf("A: pid = %d", pid);
printf("B: pid1 = %d", pid1);
}
else {
printf("C: pid = %d", pid);
wait(NULL);
pid2 = fork();
if(pid2 == 0) {
printf("D");
}
else {
wait(NULL);
printf("E: pid2 = %d", pid2);
}
}
return 0;
}
2: List all of the possible outputs (just write the A/B/C/D/E indicators for each printf that will run; no need for pids) that could be generated by the previous program. Again assume that fork will always succeed.
Explanation / Answer
int main() {
//let pid be the process that called the main and pid =2600
pid_t pid, pid1, pid2;
pid = fork();
pid1 = getpid();//pid1 = 2600
if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) {
printf("A: pid = %d", pid);//here pid =0//because its child process
printf("B: pid1 = %d", pid1);//pid1 is 2600
}
else {
//parent process
printf("C: pid = %d", pid);//pid is a positive value that is greater than 0
wait(NULL);//waits for child
pid2 = fork();//calling for agiain
if(pid2 == 0) {
printf("D");//pid2 is 0
}
else {
wait(NULL);
printf("E: pid2 = %d", pid2);//pid2 is 0
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.