So I’ve been working on this today and I’m pretty sure I’m close, but I’m still a bit confused on how to terminate child processes and if I’m doing this assignment correctly. Here’s the problem description:
Write a UNIX program that creates a child process that
prints a greeting, sleeps for 20 seconds, then exits.
The parent process should print a greeting before creating
the child, and another after the child has terminated. It
should then terminate.
And here’s the code that I have:
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int child;
printf("Parent Greeting\n");
child = fork();
if(child >= 0)
{
if(child == 0)
{
printf("Child process\n");
sleep(2);
printf("Child exiting\n");
exit(0);
}
}
else
{
printf("Failed\n");
}
printf("End");
exit(1);
return 0;
}
The issue I’m running into is how to properly terminate the child process. If I have the exit statements commented out, then the child will run, wait, and then the “End” statement will print. If I have the exit statements in, then the child process will say that it’s exiting and the program will just sit until I ctrl+c out of it. Any help would be appreciated, as I’m interested in the topic but am a bit confused 🙂 Thank you!
You don’t have to terminate the child process from the parent; it should terminate itself (and does after the
sleep(),printf()andexit()). The parent process shouldwait()orwaitpid()for the child to die before it prints the"End"message. Also, your"End\n"message should include a newline.The
exit(1);(at the end of the first program) is not wanted; it indicates failure. Theexit()function does not return, so as written thereturnis redundant. But it would be better to remove theexit()and leave thereturn 0;indicating success.(Note that the child should include a call to
exit(), probably with the value 0 rather than 1 as in the revised code. After all, it has done its job successfully.)