进程之间的通信
无名管道
无名管道其实是一个数组来的,里面存放着读端与写端的文件描述符。作用范围有亲缘关系的两个进程。
初始化无名管道
man 2 pipe
pipefd: 具有两个int类型成员的数组的首元素地址。
返回值:
成功:0
失败:-1
int fd[2];
pipe(fd); 结果: fd[0]->读端 fd[1]->写端
实现使用无名管道,使得父子进程之间通信。
int main()
{
int ret;
pid_t x;
int fd[2] = {0}; //fd[0] = 0 fd[1] = 0
ret = pipe(fd);
if(ret != 0)
{
printf("pipe error!\n");
}
printf("fd[0] = %d\n",fd[0]);
printf("fd[1] = %d\n",fd[1]);
x = fork();
if(x > 0)
{
char buf[10];
read(fd[0],buf,sizeof(buf));
printf("buf:%s\n",buf);
wait(NULL);
exit(0);
}
if(x == 0)
{
char buf[10] = "hello";
write(fd[1],buf,strlen(buf));
exit(0);
}
return 0;
}
有名管道
有名管道是一个文件,作用范围是整个系统中任意的两个进程!
mkfifo()
man 3 mkfifo
功能:make a FIFO special file 管道文件是一种特殊的文件,不同于普通文件。
pathname:需要创建的管道文件的路径
mode:八进制权限
返回值:
成功:0
失败:-1
实现1.c文件发送数据给2.c。
1.c ->读端
int main()
{
umask(0000);
int ret = mkfifo("/home/gec/test_fifo",0777);
if(ret == -1)
{
printf("mkfifo error!\n");
}
int fd = open("/home/gec/test_fifo",O_RDWR);
if(fd < 0)
{
printf("open error!\n");
}
char buf[100] = {0};
read(fd,buf,sizeof(buf));
printf("from fifo:%s",buf);
close(fd);
return 0;
}
2.c写端
int main()
{
int fd = open("/home/gec/test_fifo",O_RDWR);
if(fd < 0)
{
printf("open error!\n");
}
char buf[50] = {0};
fgets(buf,50,stdin); //最多从键盘中获取50个字节 -> 包含\n在内
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
无论哪个程序先运行都可以,创建之前判断管道是否存在。