Assume a foo program has the following codes. int main() { if ((pid=fork())==0)
ID: 3817308 • Letter: A
Question
Assume a foo program has the following codes. int main() { if ((pid=fork())==0) printf("child "); else if (pid>0) printf("parent "); } If we run foo twice in bash as the command "./foo ; ./foo", we may get one of the following results. Note that you may not observe the same results in your own computer. The second result can happen because bash will execute the second foo when the parent process in the first foo finishes. Note that you CANNOT assume the parent process will always be executed before the child process. result 1 : parent child parent child result 2 : parent parent child child result 3 : child parent child parent result 4 : child child parent parent a) Modify the codes so that only result 2 will happen. (Hint: use sleep()) b) Modify the codes so that only result 1 will happen. (Hint: use wait()) c) Modify the codes so that only result 3 will happen. d) Discuss and explain whether result 4 could happen or not.
Explanation / Answer
a) Modify the codes so that only result 2 will happen. (Hint: use sleep())
int main() {
int pid;
if ((pid=fork())==0)
{
sleep(1); //This step will make sure that child will be printed after parent is printed twice.
printf("child ");
}
else if (pid>0)
printf("parent ");
}
b) Modify the codes so that only result 1 will happen. (Hint: use wait())
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pid;
if ((pid=fork())==0)
{
wait(&pid);
printf("child ");
}
else if (pid>0)
{
//wait(&pid);
printf("parent ");
}
}
c) Modify the codes so that only result 3 will happen.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pid;
if ((pid=fork())==0)
{
//wait(&pid);
printf("child ");
}
else if (pid>0)
{
wait(&pid);
printf("parent ");
}
}
d) Discuss and explain whether result 4 could happen or not.
Result 4 could not happen. The reason is simple.
The program starts execution at main(), and unless the main() i.e., the parent process,
comes to an end, the next execution will not start, and therefore, it is not possible to
start the next process execution without ending the previous one.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.