#include<stdio.h> #include<unistd.h> #include<string.h> #include<stdlib.h> int main() { int fd[2];//定义数组 int pid; char buf[128]; if(pipe(fd)==-1){//创建管道 printf("chuang jian failed\n");//如果管道的值为负数那么创建失败 } pid = fork();//创建进程 if(pid<0){ printf("jincheng child failed\n");//为负数的话,创建失败 } else if(pid>0){//父进程 sleep(3);//睡3秒 printf("this is father\n"); close(fd[0]);//关闭读 write(fd[1],"hello from father",strlen("hello fro father\n"));//写入 wait();//等待回收子进程,避免产生僵尸进程 }else{//子进程 printf("this is child\n"); close(fd[1]);//关闭写 read(fd[0],buf,128);//读取父进程往管道中写的数据 printf("read from father: %s\n",buf);//打印管道中数据 exit(0);//退出子进程 return 0; } } ~
输出显示:
this is child等待3秒后
this is father
read from father: hello from father
无名管道不能同时进程读写,只能单个读写,另外为关闭
fd[0]为读
fd[1]为写