1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define READ_END 0
#define WRITE_END 1
int
main(int argc, char **argv)
{
int pipefd[2], c, i = 0, status;
char buf[4096];
pid_t pid;
/* This pipe will be connected to our child's stdin */
if (pipe(pipefd)) {
perror("pipe");
return 1;
}
pid = fork();
if (pid == -1) { /*** Error ***/
perror("fork");
return 0;
} else if (pid == 0) { /*** Child ***/
/* Close write end of pipe */
close(pipefd[WRITE_END]);
/* Connect read end of pipe to stdin */
if (-1 == dup2(pipefd[READ_END], STDIN_FILENO)) {
perror("dup2");
return 1;
}
close(pipefd[READ_END]);
/* Execute user-provided command */
execvp(argv[1], argv + 1);
perror("execvp");
return 1;
} else { /*** Parent ***/
/* Close read end of pipe */
close(pipefd[READ_END]);
/* Read data on stdin, sending them to the child process
* every time a newline is read */
while ( (c = getchar()) != EOF ) {
buf[i++] = c;
if (c == '\n') {
if (i != write(pipefd[WRITE_END], buf, i)) {
perror("write");
return 1;
}
i = 0;
}
}
if (c != EOF) {
perror("getchar");
return 1;
}
/* Closing the pipe will signal EOF in the child */
close(pipefd[WRITE_END]);
/* Wait for child */
wait(&status);
if ( (!WIFEXITED(status)) || (WEXITSTATUS(status) != 0) ) {
fputs("Child process terminated abnormally\n", stderr);
return 1;
}
}
return 0;
} |
Partager