使用轮询无法从命名管道中读取一个以上的单词

标签 c ipc named-pipes system-calls polling

我正在模拟有两个作者和一个读者,基于这个 answer .

因此,我创建了两个管道,并向每个管道写入了一个实际的字符串,还有一个字符串通知读者他已完成与该编写器的交互。

但是,它只会读取第一个字符串,有时还会读取第二个管道的结尾字符串。

我错过了什么?

reader.c

int main() {
    int w_no = 2;
    int fd[w_no];
    char * myfifo[w_no];
    fill_names(myfifo, w_no);
    print_names(myfifo, w_no);
    struct pollfd fdtab[w_no];
    int done[w_no];

    /* create the FIFO (named pipe) */
    int i;
    for (i = 0; i < w_no; ++i) {
        //fd[i] = open(myfifo[i], O_RDONLY);
        while( (fd[i] = open(myfifo[i], O_RDONLY)) == -1); 

        fdtab[i].fd = fd[i];
        fdtab[i].events = POLLIN;
        fdtab[i].revents = 0;

        done[i] = 0;
    }

    char buffer[1024];
    ssize_t bytes;
    printf("Edw prin\n");
    while(not_all_done(done, w_no)) {
        int retpoll = poll(fdtab,  w_no, 300);
        if(retpoll != 0) {
             if (retpoll == -1) {
                 perror("poll");
                 break;
             }

             for(i = 0; i < w_no; ++i) {
                 if(fdtab[i].revents & POLLIN) {
                            printf("Edw %d %d %d %d\n", i, retpoll, fdtab[i].revents, POLLIN);
                     //read the written pipe
                     while((bytes = read(fdtab[i].fd, buffer, sizeof(buffer))) > 0)
                        printf("Read |%s| %d %d %d\n", buffer, retpoll, fdtab[i].revents, POLLIN);
                     if(!strcmp(buffer, "++"))
                        done[i] = 1;
                 }
             }
         } else if (retpoll == 0) {
                /* the poll has timed out, nothing can be read or written */
                printf("timeout from writer\n");
                break;
            }
    }

    for (i = 0; i < w_no; ++i) {
        close(fd[i]);
    }

    free_names(myfifo, w_no);
    return 0;
}

writer.c

int main() {
    int w_no = 2;
    int fd[w_no];
    char * myfifo[w_no];
    fill_names(myfifo, w_no);
    print_names(myfifo, w_no);

    /* create the FIFO (named pipe) */
    int i;
    int bytes;
    for (i = 0; i < w_no; ++i) {
      mkfifo(myfifo[i], 0666);
        fd[i] = open(myfifo[i], O_WRONLY);

        while( (bytes = write(fd[i], "Hi+", sizeof("Hi+"))) == 3);
        printf("wrote %d bytes, %d\n", bytes, sizeof("Hi+"));
        while( (bytes = write(fd[i], "++", sizeof("++"))) == 2);
        printf("wrote %d bytes, %d\n", bytes, sizeof("++"));
    }

    for (i = 0; i < w_no; ++i) {
        close(fd[i]);
        unlink(myfifo[i]);
    }

    free_names(myfifo, w_no);
  return 0;
}

示例输出:

/tmp/myfifo_0
/tmp/myfifo_0
/tmp/myfifo_1
/tmp/myfifo_1
wrote 4 bytes, 4
wrote 3 bytes, 3
wrote 4 bytes, 4
Edw prin
wrote 3 bytes, 3
Edw 0 2 17 1
Read |Hi+| 2 17 1
Edw 1 2 1 1
Read |Hi+| 2 1 1
^C

编辑

Hi+ 字符串到达​​时,bytes 的值为 7。

我试图发送的结束字符串是 ++,但它没有被读取。


EDIT_2

char* concat(char *s1, char *s2) {
  char *result = malloc(strlen(s1) + strlen(s2) + 1);  //+1 for the null-terminator
  //in real code you would check for errors in malloc here
  strcpy(result, s1);
  strcat(result, s2);
  return result;
}

void fill_names(char* f[], int n) {
  int i = 0;
  char * buf = "/tmp/myfifo_";
  char str[15];
  for (; i < n; ++i) {
    sprintf(str, "%d", i);
    f[i] = concat(buf, str);
  }
}

想法

也许作者在从管道中读取数据之前关闭并取消了管道链接?如果是这样,我应该怎么做才能防止这种情况发生?

如果在此之前放置一个sleep(10),它不会改变行为,它只会读取前两个字符串,但会花费更多时间然后挂断(因为它等待结束字符串)。


EDIT_3

我还有一个 main.c,它执行读取器和写入器。

最佳答案

你的字符串写法有问题:

    while( (bytes = write(fd[i], "Hi+", sizeof("Hi+"))) == 3);
    printf("wrote %d bytes, %d\n", bytes, sizeof("Hi+"));
    while( (bytes = write(fd[i], "++", sizeof("++"))) == 2);
    printf("wrote %d bytes, %d\n", bytes, sizeof("++"));

此处发送 7 个字节:H i +\0++\0 ,因为字符串文字的 sizeof() 包含空终止符。

顺便说一句,只要可以写入 3 个字节,while((bytes=write(...))==3) 就会循环。这不会发生在这里,因为你的写作也是空终止符。但最好删除封闭的 while

由于管道是流,因此无法保证您会在两次不同的读取中收到字节。事实上,您所有的解释和日志都显示您一次收到所有 7 个字节。

但是,您使用 printf("Read |%s| %d %d %d\n"...) 打印内容:打印包含 '\0"未定义。在您的情况下,打印的字符串被截断。因此仅打印“Hi+”,但“\0++”仍隐藏在缓冲区中。

顺便说一句,while((bytes = read(...)) > 0) 可以循环并打印多次。这本身不是问题。只是writer发送数据及时,连续读可能会暂时锁住其他pipe的读。通常在轮询程序中,人们更喜欢从每个就绪的管道中读取一点点。

检查结束字符串

    if(!strcmp(buffer, "++"))
          done[i] = 1;

在大多数情况下可能不会成功。您不确定一侧的写入会导致另一侧读取。所以你的“++”字符串不一定在缓冲区的开头。它可能位于缓冲区中的任何位置,因此您必须搜索它。它甚至可以分为两个连续的读取。

顺便说一下,read() 可能只找到部分数据(例如:“i+”)而没有终止 null。如果您随后假设其中有一个有效字符串并尝试打印您的缓冲区,您将面临缓冲区溢出的风险。

建议:

如果你的命名管道是用来处理文本数据的,我建议在你要发送的每组数据的末尾添加一个'\n',并将字符串写入没有终止空的管道:

bytes = write(fd[i], "Hi+\n", sizeof("Hi+\n")-1);

然后,当您读取时,您可以像管理字符串一样管理缓冲区:始终添加尾随 0:

bytes = read(fdtab[i].fd, buffer, sizeof(buffer)-1);  // leave a byte for terminator
if (bytes>0) {
    buffer[bytes]=0; // end of string.  
    // process the string in the buffer
}
else if (bytes==0) {
    done[i]=1; 
} 

最后,为了识别您的结束命令,假设您已将其作为“++\n”发送,则存在三种可能性:

if (strncmp(buffer,"++\n",3)==0  /* it's at the beginning of the buffer */ 
      || strstr(buffer, "\n++\n") )    /* it's in the middle but not a subpart and preceded by a packet separator */
       done[i]=1;   

但是您还必须检查两次读取之间的拆分。这更微妙,但我相信你会找到办法 ;-)

关于使用轮询无法从命名管道中读取一个以上的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26952722/

相关文章:

c - `close(fd)` 是否破坏文件表条目和/或 vnode 表条目?

c - 传递给函数时的动态对象(C 指针处理)

c# - 在 C# 和 C 之间进行进程间通信的最简单方法是什么?

c# - 在意外丢失或崩溃后重新连接到 NamedPipeServerStream

sql-server - 使用SMO .net通过DeviceType.Pipe进行备份和恢复

c# - 通过 c#/dotnet 核心中的命名管道卸载到 ffmpeg

c - 在 strncpy 或类似工具上使用 memcpy 是不好的做法吗?

c++ - OpenGL "black screen"挫折

c++ - 使用 sleep() 时生产者消费者(使用 Monitor)代码不工作?

node.js - 将消息发送到Electron的父窗口