4

Launch a child process and wait for it

  1. /*
  2.  * Forks and waits for child.
  3.  *
  4.  *   fork
  5.  *   wait
  6.  *   WEXITSTATUS
  7.  *   getpid
  8.  *   sleep
  9.  */
  10.  
  11. #include <sys/types.h>
  12. #include <sys/wait.h>
  13. #include <unistd.h>
  14.  
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <errno.h>
  18. #if defined( LINUX )
  19. #include <string.h>
  20. #endif
  21.  
  22. #define SLEEPTIME               2               /* in secs */
  23.  
  24. int main( int argc, char **argv ) {
  25.     int pid, status, died;
  26.  
  27.     fprintf( stdout, "%i running...\n", getpid() );
  28.  
  29.     pid = fork();
  30.  
  31.     if ( pid == -1 ) { /* error */
  32.         fprintf( stderr, "%s\n", strerror( errno ) );
  33.         exit( 1 );
  34.     }
  35.  
  36.     if ( pid == 0 ) { /* child */
  37.         fprintf( stdout, "%i sleeping for %i secs...\n", getpid(), SLEEPTIME );
  38.         sleep( SLEEPTIME );
  39.         /* exit with an error half the time */
  40.         exit( getppid() & 1 );
  41.     }
  42.  
  43.     /* wait for child */
  44.     fprintf( stdout, "%i waiting for %i...\n", getpid(), pid );
  45.     died = wait( &status );
  46.     fprintf( stdout, "%i exited with status %i\n", died, WEXITSTATUS( status ) );
  47.     fprintf( stdout, "%i bye\n", getpid() );
  48.  
  49.     exit( 0 );
  50. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].