C 101: Preventing Zombie Processes  
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
pid_t pid;
int status;

pid = fork();

if(pid<0)
{
printf("Error: fork() returned %u.\n", pid);
return 1;
}

if(pid == 0)
{
printf("Child: PID is %u. Parent's PID is %u\n", getpid(), getppid());
sleep(10);
puts("Child: about to exit.\n");
return 33;
}
else
{
printf("Parent: PID is %u. Child's PID is %u\n", getpid(), pid);

while((pid=waitpid(-1,&status,WNOHANG)) == 0)
{
printf("Parent: No child has terminated.");
printf("Parent: Going to sleep for 1 second.\n");
sleep(1);
}
}

printf("Parent: child with PID %u ", pid);

if(WIFEXITED(status)!=0)
{
printf("exited with status %u\n",WIFEXITED(status));
}
else
{
printf("exited abnormally\n");
}

return 0;
}

Preventing Zombie Processes Using waitpid()
Listing 19.5 -Teach Yourself C For Linux Programming
[acool@localhost C-practice]$ gcc -Wall fork.c
[acool@localhost C-practice]$
[acool@localhost C-practice]$ ./a.out
Parent: PID is 57544. Child's PID is 57545
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Child: PID is 57545. Parent's PID is 57544
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Parent: No child has terminated.Parent: Going to sleep for 1 second.
Child: about to exit.

Parent: child with PID 57545 exited with status 1
[acool@localhost C-practice]$
[acool@localhost C-practice]$


Comments
Comments are not available for this entry.
2024 By Angel Cool