Waiting for a child to die
Mayank Jain <[email protected]> Sat, 24 Dec 2005 21:46:14 +0530
| Newsgroups | gmane.user-groups.linux.delhi.devel,gmane.user-groups.linux.delhi |
|---|---|
| Message-ID | <[email protected]> |
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>
int main()
{
pid_t child =3D 0;
int status =3D 0;
printf("forking!\n");
child =3D fork();
if(child =3D=3D 0)
{
printf("Inside child\n");
sleep(2);
printf("Finishing if\n");
}
else
{
printf("Inside Parent\n");
while(1)
{
printf("Calling waitpid\n");
waitpid(child, &status, 0);
if(WIFEXITED(status))
{
printf("Child exited\n");
break;
}
}
printf("Finishing else\n");
}
}
The above code works perfectly, the parent waits for the child to die
& then exits itself.
root@Warrior:~/junk# ./child
forking!
Inside child
Inside Parent
Calling waitpid
Finishing if
Child exited
Finishing else
root@Warrior:~/junk#
However, how do i make this wait by the parent a non-blocking wait?
This is because while checking for "has the child died", parent is
blocked by waitpid & hence cannot do other processing.
I've tried using WNOHANG in waitpid as waitpid(child, &status,
WNOHANG) & this is the output i get
root@Warrior:~/junk# ./child
forking!
Inside child
Inside Parent
Calling waitpid
Child exited
Finishing else
root@Warrior:~/junk#
root@Warrior:~/junk# Finishing if
root@Warrior:~/junk#
Notice that parent exited before child died.
Am i using WNOHANG in a wrong way? or in a wrong place? What can be
other strategies i can use? I dont want to use threads as they'll be
an overkill (all i want to do is keep parent in non-blocking state,
while looping for child's alive status).
--
regards,
makuchaku
---
http://makuchaku.info
When you speak out with the courage of your convictions, people listen!
-- Valmik Thapar, Wildlife Conservationist.