我正在尝试向另一个程序发送一个字符串 但我在使用 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 进行读取,则打开将失败。
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/