【发布时间】:2016-05-19 06:20:17
【问题描述】:
我试图证明我的一个疑问,两个不相关的进程可以共享半双工管道的fd并进行通信。
我为此创建了两个程序。但后来我又问了一个问题,如果进程死亡,管道会发生什么?因为当我打印出消息时,我的读者收到了一些垃圾消息。
作家
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd[2];
char str[] = "hello\n";
if(pipe(fd) < 0)
perror("Pipe creation failed\n");
//Since i am a writer, i should close the reading end as a best practice
close(fd[0]);
/*
The processes need not to be related processes, in order to use the half duplex pipes. fd is just a number/identifier
which can be shared across different processes
*/
printf("Hey there !!! use this file descriptor for reading : %d\n", fd[0]);
//writing message
write(fd[1],str,strlen(str)+1);
return 0;
}
阅读器
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd,bytesRead;
char buffer[1024];
printf("please enter the fd :");
scanf("%d",&fd);
bytesRead = read(fd,buffer,1024);
printf("Bytes Read : %d\nMessage : %s\n", bytesRead, buffer);
return 0;
}
【问题讨论】:
-
行不通。 fd 编号是进程本地的,因此不相关的进程无法共享它们。 (我的标准输入是我的!打开 fd 0 无法读取它。)使用命名管道或 fifo。
-
阅读器没有“读取垃圾值”,阅读器无法读取任何内容,而您没有注意到是因为您没有检查错误。