- #define _GNU_SOURCE
- #include <unistd.h>
- #include <signal.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stddef.h>
- #include <stdint.h>
- #include <stdbool.h>
- #define ERR_EXIT(m) \\
- do \\
- { \\
- perror(m); \\
- exit(EXIT_FAILURE); \\
- } while(0)
- int
- main(int argc,char *argv[])
- {
- //这里使用管道的系统调用来模拟
- //日常常见的命令行管道调用。例
- //如:ls | wc -w
- int pipefd[2];
- if(-1 == pipe(pipefd))
- ERR_EXIT("pipe error");
- pid_t pid;
- pid = fork();
- if(-1 == pid)
- ERR_EXIT("fork error");
- if(0 == pid) {
- //使用文件描述符复制的方法来使用管道
- dup2(pipefd[1],STDOUT_FILENO);//复制写端
- close(pipefd[1]);
- close(pipefd[0]);
- execlp("ls","ls",NULL);
- fprintf(stderr,"error execute ls\\n");
- exit(EXIT_FAILURE);
- }
- dup2(pipefd[0],STDIN_FILENO);//复制读端
- close(pipefd[0]);
- close(pipefd[1]);
- execlp("wc","wc","-w",NULL);
- fprintf(stderr,"error execute wc\\n");
- exit(EXIT_FAILURE);
- }
- //该片段来自于http://www.codesnippet.cn/detail/1808201410198.html
来源: http://www.codesnippet.cn/detail/1808201410198.html