[英]LINUX FIFO named pipe (IPC) stops writing/reading message at specific file descriptor
我正在使用命名管道(fifo 模式)在两个不相关的进程(不是来自同一个父进程)之间进行通信。 该程序有效。 不过堆文件好像有限制
作者的输出:
Wrote to file. fd = 3
Wrote to file. fd = 3
...... other output ...
Wrote to file. fd = 3
Wrote to file. fd = 3
读取器的输出为:
fd: 3. Received buffer: hello
fd: 4. Received buffer: hello
...... other output ...
fd: 1021. Received buffer: hello
fd: 1022. Received buffer: hello
fd: 1023. Received buffer: hello
我的问题:在fd
1023 处,读者似乎停止从文件中读取(没有fd
1024、1025 等)。 当它发生时,writer STOP WRITING(日志“Wrote to file.fd = 3”停止显示)
我尝试了不同的msg
值(“嗨”、“你在哪里”...),但作者总是停在fd
1023
我真的不明白为什么。 你能帮我解释一下吗? 非常感谢!
这是我的代码: 作者:
#include <stdio.h>
#include <stdlib.h> /* exit functions */
#include <unistd.h> /* read, write, pipe, _exit */
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char msg[] = "hello";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
fd = open(myfifo, O_WRONLY);
if (fd < 0) {
return;
}
while(1) {
write(fd, msg, sizeof(msg));
printf("Wrote to file. fd = %d\n", fd);
sleep(1);
}
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
读者:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 500
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
while(1) {
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
if (fd != -1) {
if (read(fd, buf, sizeof(buf)) > 0) {
printf("fd: %d. Received buffer: %s\n", fd, buf);
}
}
sleep(0.2);
}
close(fd);
return 0;
}
我真的不明白为什么。 你能帮我解释一下吗?
系统上打开的文件描述符的数量是有限制的。 可以使用ulimit -n
在 shell 中检查限制。 它是可配置的。 请参阅help ulimit
和man limits.conf
。
在您的系统上,打开的文件描述符的最大数量似乎是 1024(在我的也是如此!)打开更多将返回-1
和errno=EMFILE
。
您的reader
程序会在循环中打开新的文件描述符。 达到打开文件描述符的限制后, open
开始重新调整-1
,因为if (fd != -1) {
使程序停止输出任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.