8

Lancer et attendre un processus fils

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

Commentaires

Votre commentaire :
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip aide 2000

Entrez un maximum de 2000 caractères.
Améliorez la présentation de votre texte avec les balises de formatage suivantes :
[p]paragraphe[/p], [b]gras[/b], [i]italique[/i], [u]souligné[/u], [s]barré[/s], [quote]citation[/quote], [pre]tel quel[/pre], [br]à la ligne,
[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]commande[/code], [code=langage]code source en c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].