4

Launch a child process and run a command

  1. /*
  2.  * Forks and execs date command.
  3.  *
  4.  *   fork
  5.  *   execl
  6.  *   wait
  7.  *   WEXITSTATUS
  8.  */
  9.  
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include <unistd.h>
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <errno.h>
  17. #if defined( LINUX )
  18. #include <string.h>
  19. #endif
  20.  
  21. #define PROGPATH                "/usr/bin/date"
  22. #define PROGNAME                "date"
  23.  
  24. int main( int argc, char **argv ) {
  25.     int pid, status, died;
  26.  
  27.     pid = fork();
  28.  
  29.     if ( pid == -1 ) { /* error */
  30.         fprintf( stderr, "%s\n", strerror( errno ) );
  31.         exit( 1 );
  32.     }
  33.  
  34.     if ( pid == 0 ) { /* child */
  35.         execl( PROGPATH, PROGNAME, (void *) 0 ); /* shouldn't return */
  36.         /* error! */
  37.         fprintf( stderr, "%s\n", strerror( errno ) );
  38.         exit( 1 );
  39.     }
  40.  
  41.     /* wait for child */
  42.     died = wait( &status );
  43.     exit( WEXITSTATUS( status ) );
  44. }

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