我正试图写两个程序,将通过FIFOs通信在C。我正在试验FIFOs的一个任务,我有。
当我知道消息的数量并用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调用的数目不一定与write调用的数目相同。
如果我们修改读卡器以打印接收的字节数:

int len;
while((len=read(fd, buf, MAX_BUF)) > 0) {
    printf("Received %d: %s\n", len, buf);
}

我得到以下输出:
Received 30: Hi

因此在第二种情况下,有10次写入3字节(2次写入Hi的字母,1次写入空终止字节)和1次读取30字节。每个write调用写入3个字节的原因是字符串常量"Hi"具有类型char [3]
您只看到一个“Hi”实例被打印出来,因为第三个字节是一个空字节,它终止了字符串,所以不会打印超过这个值的内容。

09-09 20:35
查看更多