我有一个在一边打开读取,在另一边打开,读取侧关闭他打开的fd。有没有办法知道读者是否在作家方面关闭了这个fd? 我希望作者会有关于阅读器是否准备好阅读的任何通知,因为如果不是我的作家将被写入阻止。 writer.c:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char * myfifo = "/tmp/fifo_pipe";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hey", sizeof("Hey"));
/*here is there a posibilty of know that the read side hase close hi's side of the pipe before write? */
write(fd, "test\n", strlen("test\n"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
reader.c:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/fifo_pipe";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}
答案 0 :(得分:1)
在没有读卡器的FIFO中写入将引发SIGPIPE并最终返回-1并将errno设置为EPIPE
。
答案 1 :(得分:0)
您可以使用 lsof 系统命令检查有关进程打开的文件的信息。提取lsof命令输出的FD字段并继续。 有关更多详细信息和示例,请参阅此link
在您的情况下,要获取侦听fifo的进程数,请尝试执行以下系统命令。
lsof /tmp/fifo_pipe | grep [0-9]r | wc -l
在C中,您可以实现以下内容:
int i = 0;
FILE *fp;
char *command = "lsof /tmp/rjfifo | grep [0-9]r | wc -l";
fp = popen(command,"r");
if (fp != NULL){
fscanf(fp,"%d",&i);
}
fclose(fp);
printf("Number of processes reading /tmp/fifo_pipe = %d \n",i);