10
Run a command in a child process and display its output
- /*
- * Pipes date command output to parent.
- *
- * pipe
- * fork
- * execl
- * dup
- * dup2
- * wait
- * WEXITSTATUS
- */
- #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 PROGPATH "/usr/bin/date"
- #define PROGNAME "date"
- int main(int argc, char **argv) {
- int pid, status, died;
- int pipeline[2];
- char buf[64];
- if (pipe(pipeline) == -1) {
- fprintf(stderr, "%s\n", strerror(errno));
- exit(1);
- }
- pid = fork();
- if (pid == -1) { /* error */
- fprintf(stderr, "%s\n", strerror(errno));
- exit(1);
- }
- if (pid == 0) { /* child */
- #if 0
- close( 1 );
- dup( pipeline[ 1 ] );
- #else
- dup2(pipeline[1], 1);
- #endif
- execl(PROGPATH, PROGNAME, (void *) 0); /* shouldn't return */
- /* error! */
- fprintf(stderr, "%s\n", strerror(errno));
- exit(1);
- }
- /* read command output */
- #if 0
- read( pipeline[ 0 ], buf, sizeof( buf ) );
- #else
- dup2(pipeline[0], 0);
- fgets(buf, sizeof(buf), stdin);
- #endif
- /* print */
- fputs("Today is ", stdout);
- fputs(buf, stdout);
- /* wait for child */
- died = wait(&status);
- exit(WEXITSTATUS(status));
- }
Comments