【发布时间】:2015-12-03 14:46:46
【问题描述】:
我写了一些代码来练习管道的使用,遇到了一些问题。
对于下面的代码,我尝试创建一个命名管道来写入/读取。但是如果我的文本文件中有一些单词,我的代码就不起作用。我预计输出会打印出文本文件中的单词和我写入的字符串。我不能使用 .txt 文件作为管道吗?如何使用管道修改文本文件?感谢您的帮助!
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAX 100
int main()
{
int fd;
char *myfifo = "pipe_tx2.txt";
char buf[MAX];
/* create the fifo */
mkfifo(myfifo, 666);
/* write string to the pipe */
fd = open(myfifo, O_WRONLY);
write(fd, "hello", sizeof("hello"));
close(fd);
/* read and display message from pipe */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX);
printf("we got: %s\n", buf);
close(fd);
/* remove the pipe */
unlink(myfifo);
return 0;
}
【问题讨论】:
-
您没有检查来自
mkfifo()、write()或read()的返回值。所以你不知道什么有效,什么无效。你甚至不知道你的open()调用是否成功。 -
我不确定我是否理解您所说的“如果我的文本文件中有一些单词,我的代码将无法正常工作”是什么意思。您是说您有一个与您尝试创建的 FIFO 同名的现有常规文件吗?如果是这样,那么不,那绝对行不通。 FIFO 是文件的一种特殊种类,而不是文件的特殊用途。
-
666是十进制,但应该是八进制0666 -
如果已有同名文件,
mkfifo将返回-1(失败)并设置errno = EEXIST。 -
您的意思是使用“.txt”扩展名来命名命名管道?当然可以,标准 Unix 文件系统中没有文件扩展名的概念,任何字符串都可以命名任何类型的 file。