10

Run a command in a child process and display its output

  1. /*
  2.  * Pipes date command output to parent.
  3.  *
  4.  *   pipe
  5.  *   fork
  6.  *   execl
  7.  *   dup
  8.  *   dup2
  9.  *   wait
  10.  *   WEXITSTATUS
  11.  */
  12.  
  13. #include <sys/types.h>
  14. #include <sys/wait.h>
  15. #include <unistd.h>
  16.  
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <errno.h>
  20. #if defined( LINUX )
  21. #include <string.h>
  22. #endif
  23.  
  24. #define PROGPATH                "/usr/bin/date"
  25. #define PROGNAME                "date"
  26.  
  27. int main(int argc, char **argv) {
  28.     int pid, status, died;
  29.  
  30.     int pipeline[2];
  31.  
  32.     char buf[64];
  33.  
  34.     if (pipe(pipeline) == -1) {
  35.         fprintf(stderr, "%s\n", strerror(errno));
  36.         exit(1);
  37.     }
  38.  
  39.     pid = fork();
  40.  
  41.     if (pid == -1) { /* error */
  42.         fprintf(stderr, "%s\n", strerror(errno));
  43.         exit(1);
  44.     }
  45.  
  46.     if (pid == 0) { /* child */
  47. #if 0
  48.         close( 1 );
  49.         dup( pipeline[ 1 ] );
  50. #else
  51.         dup2(pipeline[1], 1);
  52. #endif
  53.         execl(PROGPATH, PROGNAME, (void *) 0); /* shouldn't return */
  54.         /* error! */
  55.         fprintf(stderr, "%s\n", strerror(errno));
  56.         exit(1);
  57.     }
  58.  
  59.     /* read command output */
  60. #if 0
  61.     read( pipeline[ 0 ], buf, sizeof( buf ) );
  62. #else
  63.     dup2(pipeline[0], 0);
  64.     fgets(buf, sizeof(buf), stdin);
  65. #endif
  66.  
  67.     /* print */
  68.     fputs("Today is ", stdout);
  69.     fputs(buf, stdout);
  70.  
  71.     /* wait for child */
  72.     died = wait(&status);
  73.     exit(WEXITSTATUS(status));
  74. }

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