Re: Waiting for a child to die

Ritesh Raj Sarraf <[email protected]> Sat, 24 Dec 2005 11:07:31 -0800
Newsgroups gmane.user-groups.linux.delhi,gmane.user-groups.linux.delhi.devel
Message-ID <[email protected]>
Your subject line got me really confused. :-)

rrs

On Sat, 24 Dec 2005, Mayank Jain wrote:

> #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.
>
>

-- =

Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logic from one person is plagiarism, stealing from many is resear=
ch."
"Necessity is the mother of invention."


_______________________________________________
ilugd mailinglist -- ilugd-cunTk1MwBs8/[email protected]
http://frodo.hserus.net/mailman/listinfo/ilugd
Archives at: http://news.gmane.org/gmane.user-groups.linux.delhi http://www=
.mail-archive.com/ilugd-cunTk1MwBs8/[email protected]/