- 1、创建1个子进程
- 2、程通过管道与子进程连接
- 子进程的标准输出连接到管道的写端
- 主进程的标准输入连接到管道的读端
- 3、进程中调用exec(“echo”, “echo”, “hello world”, NULL)
- 4、进程中调用read(0, buf, sizeof(buf)),从标准输入中获取子进程发送的字符串,并打印出来
code:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(){pid_t pid;int fd[2];char buf[30];int count;int i=0;pipe(fd);pid=fork();if(pid<0){perror("fork():");}if(pid==0){dup2(fd[1],1);execlp("echo","echo","hello world",NULL);}else{dup2(fd[0],0);count=read(0,buf,30);write(1,buf,count);}close(fd[0]);close(fd[1]);return 0;
}