【发布时间】:2017-04-25 12:11:04
【问题描述】:
我正在尝试编写两个程序,它们将通过 C 中的 FIFO 进行通信。我正在尝试使用 FIFO 来完成我的任务。
当我知道消息的数量并使用 for 循环读取它们时,它会打印出从另一端发送的所有消息。如果我使用 while 循环,它只会发送其中两个。代码从这个问题How to send a simple string between two programs using pipes?略有改动
这行得通:
/* writer */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
/* create the FIFO (named pipe) */
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
int i;
for(i = 0; i < 10; i++)
write(fd, "Hi", sizeof("Hi"));
close(fd);
return 0;
}
还有:(已编辑)
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
mkfifo(myfifo, 0666);
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
int i;
for(i = 0; i < 10; i++)
{
int n = read(fd, buf, MAX_BUF);
printf("n = %d , Received: %s\n",n, buf);
}
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
编辑:现在打印出来
n = 18 , Received: Hi
n = 12 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
n = 0 , Received: Hi
当我将阅读器改为这个时,它不起作用:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
mkfifo(myfifo, 0666);
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
int i;
while(read(fd, buf, MAX_BUF))
printf("Received: %s\n", buf);
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
我在两个单独的终端中运行这两个程序。 当我用第二个阅读器运行它们时,它只会打印出来:
Received: Hi
Received: Hi
任何帮助将不胜感激。
【问题讨论】:
-
如果你不检查
read()的结果,你怎么知道第一个版本有效?如果它没有读取任何内容buf将保留它以前的内容 -
@IngoLeonhardt 你是对的。刚刚编辑了答案,它一直打印出 0 作为返回值。你对我应该怎么做有什么建议吗?