Type the following C program to see the function of exec() system call: #include
ID: 3711512 • Letter: T
Question
Type the following C program to see the function of exec() system call:
#include <stdio.h>
char *myargs[] = {
"ls",
"-l",
NULL
};
int main()
{
int i;
if (fork()==0)
{
execvp("ls",myargs);
printf("NEVER PRINTED ");
exit(0);
}
else
{
for (i=0;i<5;i++)
{
printf("PARENT: %d ",i);
sleep(1);
}
}
printf("DONE ");
return 0;
}
Call the above program p3.c, and compile it as follows: gcc -o p3 p3.c <Enter>.
Then execute p3 and report the output.
Questions:
3.1 What is the output of child process?
3.2 Why you don’t see the "NEVER PRINTED" message?
3.3 What is the output of parent process?
3.4 Execute p3 several times. Why sometimes the outputs of parent and child are interleaved?
3.5 How could you convert the parent to a long-running process? Convert it and then put it in the background. Report the status and PID.
4. A process can wait for one of its child processes to finish by executing the wait() system call. The value returned by wait is the process ID of the child process that terminated. If the process that calls wait() does not have any child process, wait returns the value of –1 immediately. If the process that calls wait has one or more child processes that has not yet terminated, then the calling process is suspended by the kernel until one of its child processes terminates. When a child process terminates and wait returns, if the status argument is not NULL, the value passed to exit() by the terminating child process is stored in the status variable.
Explanation / Answer
3.1 What is the output of child process?
Answer:
The child process never runs
3.2 Why you don’t see the "NEVER PRINTED" message?
Answer:
The child process does not run. The parent process is replaced with another process
3.3)What is the output of parent process?
Answer:
PARENT: 0
ls: cannot access l: No such file or directory
PARENT: 1
PARENT: 2
PARENT: 3
PARENT: 4
DONE
3.4 Execute p3 several times. Why sometimes the outputs of parent and child are interleaved?
Answer:
The timing of parent with respect to child is undefined. The output from parent could print before, interleaved, or after the output from child.
3.5 How could you convert the parent to a long-running process?
Answer:
Convert it and then put it in the background. Report the status and PID.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.