4
Launch a child process and wait for it
- /*
- * Forks and waits for child.
- *
- * fork
- * wait
- * WEXITSTATUS
- * getpid
- * sleep
- */
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #define SLEEPTIME 2 /* in secs */
- int main( int argc, char **argv ) {
- int pid, status, died;
- fprintf( stdout, "%i running...\n", getpid() );
- pid = fork();
- if ( pid == -1 ) { /* error */
- fprintf( stderr, "%s\n", strerror( errno ) );
- exit( 1 );
- }
- if ( pid == 0 ) { /* child */
- fprintf( stdout, "%i sleeping for %i secs...\n", getpid(), SLEEPTIME );
- sleep( SLEEPTIME );
- /* exit with an error half the time */
- exit( getppid() & 1 );
- }
- /* wait for child */
- fprintf( stdout, "%i waiting for %i...\n", getpid(), pid );
- died = wait( &status );
- fprintf( stdout, "%i exited with status %i\n", died, WEXITSTATUS( status ) );
- fprintf( stdout, "%i bye\n", getpid() );
- exit( 0 );
- }
Comments