我正在尝试使用FIFO进行处理。但是当尝试创建FIFO然后打开它时,我的程序挂起(无法退出)。
if (mkfifo("./fifo.txt", S_IRUSR | S_IWUSE) < 0) {
fprint("Can not create fifo");
return 1;
}
if ((readfd = open("./fifo.txt", O_RDONLY)) < 0) {
return 1;
}
我在这里做错了什么?
非常感谢。
答案 0 :(得分:2)
阅读fifo(7),特别是:
通常,打开FIFO块直到另一端打开。
所以我猜您对open(2)的来电被阻止了。也许您想传递O_NONBLOCK
标志。
您应该使用strace(1)调试您的程序(也可能{fif}另一端的其他程序strace
。并在出错时致电perror(3)。
在您的情况下,使用unix(7)套接字可能更具相关性。然后,您可以在poll(2)
之前accept(2)答案 1 :(得分:0)
以下是一个示例代码:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void child(void)
{
int fd = 0;
if ((fd = open("./fifo.txt", O_WRONLY)) < 0) {
return;
}
write(fd, "hello world!", 12);
}
void parent(void)
{
int fd = 0;
if ((fd = open("./fifo.txt", O_RDONLY)) < 0) {
return;
}
char buf[36] = {0};
read(fd, buf, 36);
printf("%s\n", buf);
}
int main(void)
{
pid_t pid = 0;
if (mkfifo("./fifo.txt", S_IRUSR | S_IWUSR) < 0) {
printf("Can not create fifo\n");
return 1;
}
pid = fork();
if (pid == 0) {
printf("child process\n");
child();
} else if (pid < 0) {
printf("fork error\n");
return -1;
}
parent();
}