使用命名管道在两个程序之间发送字符串

时间:2013-09-30 18:20:48

标签: c named-pipes

我正在尝试将字符串发送到另一个程序 但我使用O_WRONLY |时遇到问题O_NONBLOCK, 如果我用O_RDWR替换它,该程序工作正常 但我想知道是否有办法发送/阅读 不使用O_RDWR的字符串。现在它返回一个 由于某种原因空字符串。

编剧:

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>

 #define MAX_LINE 1024

 int main(int argc, char **argv)
 {
     char line[MAX_LINE];
     int pipe;
     printf("Enter line: \n");
     fgets(line, MAX_LINE, stdin);
     pipe = open("link1", O_WRONLY | O_NONBLOCK);
     write(pipe, line, strlen(line));
     system("./run"); //executing the reader
     close(pipe);
     return 0;
 }

阅读器:

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>

 #define MAX_BUF 1024

 int main(int argc, char **argv)
 {
     int fd;
     char * link1 = "link1";
     char buf[MAX_BUF];
     fd = open(link1, O_RDONLY | O_NONBLOCK);
     read(fd, buf, MAX_BUF);
     printf("%s\n", buf);
     close(fd);
     return 0;
 }

1 个答案:

答案 0 :(得分:3)

您是先运行读卡器吗?如果编写器尝试打开它时没有进程打开FIFO进行读取,则打开将失败。

来自Open Group man page

  

当打开设置了O_RDONLY或O_WRONLY的FIFO时:如果设置了O_NONBLOCK:   只读的open()将立即返回。如果当前没有进程打开文件进行读取,则仅用于写入的open()将返回错误。

相关问题