Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define READ_END 0
- #define WRITE_END 1
- int
- main() {
- pid_t c1_pid = fork();
- int c1_status = 0;
- int pipefd[2];
- if (pipe(pipefd) == -1) {
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- if (c1_pid < 0) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if (c1_pid == 0) {
- // child 1
- printf("first child\n");
- dup2(pipefd[WRITE_END], STDOUT_FILENO);
- close(pipefd[WRITE_END]);
- close(pipefd[READ_END]);
- printf("hello world\n");
- } else {
- // parent
- pid_t c2_pid = fork();
- int c2_status = 0;
- if (c2_pid < 0) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if (c2_pid == 0) {
- // child 2
- printf("second child\n");
- dup2(pipefd[READ_END], STDIN_FILENO);
- close(pipefd[WRITE_END]);
- close(pipefd[READ_END]);
- char* myargs[2];
- myargs[0] = strdup("/bin/cat");
- myargs[1] = NULL;
- execvp(myargs[0], myargs);
- } else {
- // parent
- pid_t finished_c2_pid = waitpid(c2_pid, &c2_status, WUNTRACED);
- printf("finished c2 process: %d\n", finished_c2_pid);
- }
- close(pipefd[WRITE_END]);
- close(pipefd[READ_END]);
- pid_t finished_c1_pid = waitpid(c1_pid, &c1_status, WUNTRACED);
- printf("finished c1 process: %d\n", finished_c1_pid);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement