管道:
- 它是半双工的(数据只能在一个方向上流动)具有固定的读端和写端。
- 它只能用于父子进程或兄弟进程之间的通信。
- 它可以看成一种特殊的文件,它的读写可以使用read和write等函数;但它不是普通文件,不属于其他任何文件系统,只存在于内存中。
- 管道数据读走就没了。
建立管道:(无名管道)
- int pipe(int fd[2]);
- 返回值:成功返回0,失败返回-1。
- 当一个管道建立时,它会创建两个文件描述符,f[0]为读而打开,f[1]为写而打开。
- fd[0]对应读: read(fd[0],__,__);
- fd[1]对应写: write(fd[1],__,__);
- 关闭管道:只需将两个文件描述符关闭即可。
- close(fd[0]); close(fd[1]);
- 管道读写时:
- 读时先关闭写:close(fd[1]);
- 写时先关闭读:close(fd[0]);
#include <unistd.h>
int pipe(int pipefd[2]);
代码如下:
#include <unistd.h>
#include <string.h>
#include <stdio.h>int main()
{
int fd[2];
int pid;
char buf[128];if(pipe(fd) == -1){
printf("pipe is fail\n");
}pid = fork();
if(pid < 0){
printf("creat fork is fail\n");
}if(pid >0){
sleep(3);
printf("this is father \n");close(fd[0]);
write(fd[1],"hello this is father",strlen("hello this is father"));
}if(pid == 0){
printf("this is child \n");close(fd[1]);
read(fd[0],buf,128);
printf("read from father:%s\n",buf);
}
return 0;
}
运行结果:
this is father
this is child
read from father:hello this is father