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

标签 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;
 }

最佳答案

您是否首先运行阅读器?如果在写入者尝试以只写方式打开 FIFO 时没有进程打开 FIFO 进行读取,则打开将失败。

来自Open Group man page :

When opening a FIFO with O_RDONLY or O_WRONLY set: If O_NONBLOCK is set: An open() for reading only will return without delay. An open() for writing only will return an error if no process currently has the file open for reading.

关于c - 使用命名管道在两个程序之间发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19101062/

相关文章:

c++ - 在文件中搜索一个单词并在 C 中替换它?

为 PuTTYTray 创建预制项目

c - 为什么arm-linux-gnueabihf-gcc和mipsel-openwrt-linux-uclibc-gcc编译 'gmtime, strftime'的结果不同

c++ - 如何创建虚拟文件?

c - C 中的命名信号量在信号处理程序调用后不会被删除

mysql - 跨平台 SQL DB API c/c++

windows - 命名管道 Matlab

c# - 如何增加命名管道的MaxStringContentLength?

c - Windows命名管道问题

windows - 我可以使用什么来代替 Unix 管道在 Windows 上进行进程间通信?