#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main (int args
ID: 3879770 • Letter: #
Question
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main (int args, char *argv[])
{
pid_t fork_return;
pid_t pid;
pid=getpid();
fork_return = fork();
// When fork() returns -1, an error happened.
if (fork_return==0)
// When fork() returns 0, we are in the child process.
{
printf("n The values are Child ID = %d, Parent ID=%d ", getpid(), getppid());
execl("/bin/cat", "cat", "-b", "-v", "-t", argv[1], 0);
}
else
// When fork() returns a positive number, we are in the parent process
// and the return value is the PID of the newly created child process.
{
wait(NULL);
printf(" Child Completes " );
printf(" In the Parent Process ");
printf("Child Id = %d, Parent ID = %d ", getpid(), getppid());
}
return 0;
}
Q1 Once this program is typed, and executed, answer the following questions
a. If you try to print a message after the exec* call, does it print it? Why? Why not?
b. Who is the parent of your executable program?
c. How would you change the code so that the child and parent run concurrently?
Explanation / Answer
If you have any problem with the answer just let me know in the comments and I'll try to solve it as soon as possible
(a). If we try to print a message after exec then it will not print anything as fork return a positive number means we are in parent process and return of fork is some negative number or positive number rather than 0.
(b). getpid will return process id of child and getppid will return parent's process ID.
(c) Appropriate parent should wait using wait and waitpid() so that it's child done it's executing. We can provide concurrent execution using sleep operations. Here I used nanosleep.
Code : #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main (int args, char *argv[])
{
pid_t fork_return;
pid_t pid;
pid=getpid();
fork_return = fork();
struct timespec tw = { .tv_sec = 0, .tv_nsec = 10000000 };
// When fork() returns -1, an error happened.
if (fork_return==0)
// When fork() returns 0, we are in the child process.
{
printf("n The values are Child ID = %d, Parent ID=%d ", getpid(), getppid());
execl("/bin/cat", "cat", "-b", "-v", "-t", argv[1], 0);
}
else
// When fork() returns a positive number, we are in the parent process
// and the return value is the PID of the newly created child process.
{
// wait(NULL);
nanosleep(&tw, 0);// for concurrent run
printf(" Child Completes " );
printf(" In the Parent Process ");
printf("Child Id = %d, Parent ID = %d ", getpid(), getppid());
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.