- 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;
}