当我的程序启动时,它只是创建一个 fifo 并打开它,之后我只想将一些信息输出到屏幕上,但是,没有任何内容被打印出来。这是我的代码片段:
void listen(const server_config_t* server_conf)
{
// Create FIFO
if (mkfifo(SERVER_FIFO_PATH, 0660) == -1) {
fprintf(stdout, "server FIFO not created as it already exists. continuing...\n");
}
// Open FIFO (for reading)
int fd;
if ((fd = open(SERVER_FIFO_PATH, O_RDONLY)) == -1) {
// fprintf(stderr, "error: could not open server FIFO\n");
perror("FIFO");
exit(1);
}
// Open dummy FIFO (for writing, prevent busy waiting)
// TODO: find way to wait without another file descriptor?
int fd_dummy;
if ((fd_dummy = open(SERVER_FIFO_PATH, O_WRONLY)) == -1) {
perror("DUMMY FIFO");
exit(1);
}
// TODO: this should print immediately after starting,
// but doesn't for some reason
fprintf(stdout, "server listening... %d %s\n", server_conf->num_threads,
server_conf->password);
fflush(stdout);
.
.
.
}
这是我的输出:
我已经尝试注释掉 fifo 的创建和打开,当我这样做时,消息会正确地打印到屏幕上。
最佳答案
打开 FIFO 通常会阻塞,直到另一端也打开,参见 http://man7.org/linux/man-pages/man7/fifo.7.html .因此,您的程序可能会在 open(SERVER_FIFO_PATH, O_RDONLY)
中等待,并且不会到达任何其他 fprintf
或 perror
。
您尝试打开 FIFO 进行先读取再写入的尝试不起作用,因为第一次打开不会返回。
当您使用调试器逐步执行程序时,您应该能够看到这一点。
顺便说一句:当mkfifo
返回-1
时,您应该检查errno
是否为EEXIST
。可能还有其他错误也会导致返回值 -1
,请参阅 https://linux.die.net/man/3/mkfifo
关于c - 创建和打开 FIFO 后 fprintf() 到 stdout 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56008726/