管道通常指无名管道,是 UNIX 系统IPC最古老的形式。
特点:
1. 它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
2. 它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
3. 它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是 它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
原型:
当一个管道建立时,它会创建两个文件描述符:fd[0]
为读而打开,fd[1]
为写而打开。
SYNOPSIS
#include <unistd.h>
int pipe(int pipefd[2]);
/*
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
*/
代码示例:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int fd[2]; //两个文件描述符
pid_t pid;
char buf[128];
if(pipe(fd) == -1) //创建管道
{
perror("pipe");
}
pid = fork(); //创建子进程
if(pid < 0)
{
perror("fork");
}else if(pid > 0) //父进程
{
sleep(3);
printf("this is father\n");
close(fd[0]); //父进程关闭读端
write(fd[1],"hello from father",strlen("hello from father"));
wait(NULL);
}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;
}