C program where parent process waits for it child to exit (using wait system call) and prints the exit status.
In the below program, the parent process wait for the child to
exit. When the child exits, the parent process would print the exit status. The
below code only prints when the child process exits due to exit(0) or when it
returns from it's main function.
Steps:
*********************************************************************
1.
*********************************************************************
Neelkanth$ cat parent_main.c
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t
child_pid;
int status;
/* now create
new process */
child_pid =
fork();
if (child_pid >= 0) /* fork succeeded */
{
if (child_pid == 0) /* fork() returns 0 for the child process */
{
printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
printf("start child process!\n");
printf("child PID = %d, parent pid = %d\n",
getpid(), getppid());
char *cmd[] = {"./child1", "neel", "rockstar", NULL};
return execvp(cmd[0], cmd); // call child1 process
}
else /* parent process */
{
printf("*****************************************************\n");
printf("parent process!\n");
printf("parent PID = %d, child pid = %d\n",
getpid(), child_pid);
/* wait for child to exit, and store child's exit status */
printf("WAIT FOR THE CHILD PROCESS TO TERMINATE\n");
printf("*****************************************************\n");
wait(&status);
/*check the child exit status: */
if (WIFEXITED(status)) {
printf("Child process has exited. exit code:
%d\n", WEXITSTATUS(status));
printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
}
printf("*****************************************************\n");
printf("Parent exits now!\n\n");
printf("*****************************************************\n");
exit(0); /* parent exits */
}
}
else /* failure
*/
{
perror("fork");
exit(0);
}
}
*********************************************************************
2.
*********************************************************************
Neelkanth$ cat child_main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
/* the program should take 2 arguments */
if (((argc >1) && (argc <= 3)))
{
printf("process name:
%s\n", argv[0]);
printf("arguments %s
%s\n", argv[1], argv[2]);
} else {
printf("enter only 2 random
strings\n");
exit(1);
}
/* The child process should run indefinitely */
printf("Child process to sleep for 10
secs\n");
sleep(10);
return 0;
}
*********************************************************************
3.
*********************************************************************
Compilation:
gcc -o child1 child_main.c
gcc -o parent_main parent_main.c