将字符串写入管道

时间:2015-10-03 06:05:05

标签: c unix pipe

我正在尝试将字符串发送到unix中的管道。当我进行逐行调试过程时,调用mkfifo()会在与源代码相同的目录中创建文件。但是,当我到达open()调用时,调试器不再能够继续。我不确定为什么它无法访问管道文件。

以下是相关代码:

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

int main()
{
int fd;
char * myfifo = "myfifo";

/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);

/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);

/* remove the FIFO */
unlink(myfifo);

return 0;
}

任何建议都表示赞赏。谢谢。

3 个答案:

答案 0 :(得分:4)

通常情况下,在任何一方可以继续之前,FIFO必须同时在两端打开。既然你没有提到有关读者的任何内容,最可能的答案是你还没有,或者你还没有设置它。一旦你这样做,开放将被允许继续。

答案 1 :(得分:1)

mkfifo(3)

fifo(7)路径为:

  

内核为至少一个进程打开的每个FIFO特殊文件保留一个管道对象。在传递数据之前,必须在两端打开FIFO(读取和写入)。 通常情况下,打开FIFO块直到另一端打开。

有一种非阻止读取的解决方案:

  

进程可以在非阻塞模式下打开FIFO。在这种情况下,即使在写入端尚未打开任何人,打开以进行只读也是成功的,只能打开与ENXIO(没有这样的设备或地址),除非另一端有已经打开了。

所以你可以分叉另一个阅读过程:

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


long strlen(char * c){
    return c[0] == 0 ? 0 : 1 + strlen(++c);
}

int main()
{
    int fd;
    int fr;
    char buf[3];
    char * MESSAGE = "Hi\n";
    char * myfifo = "myfifo";

    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);


    int msglen = strlen(MESSAGE);
    int child = fork();
    if (child == 0){
        /* read "Hi" from the FIFO (CHILD)*/
        fr = open(myfifo, O_RDONLY);
        read(fr, buf, msglen);
        write(1, buf, msglen);
        close(fr);

    } else {
        /* write "Hi" to the FIFO (PARENT)*/
        fd = open(myfifo, O_WRONLY);
        write(fd, MESSAGE, sizeof(char) * msglen);
        close(fd);

        /* remove the FIFO */
        wait(child);
        unlink(myfifo);
    }
    return 0;
}

我想你必须在写完之前打开两端。

答案 2 :(得分:0)

这里是mkfifo()手册页的摘录。最后看到我的笔记

  mkfifo() makes a FIFO special file with name pathname.  mode
   specifies the FIFO's permissions.  It is modified by the process's
   umask in the usual way: the permissions of the created file are (mode
   & ~umask).

   A FIFO special file is similar to a pipe, except that it is created
   in a different way.  Instead of being an anonymous communications
   channel, a FIFO special file is entered into the filesystem by
   calling mkfifo().

   Once you have created a FIFO special file in this way, any process
   can open it for reading or writing, in the same way as an ordinary
   file.  However, it has to be open at both ends simultaneously before
   you can proceed to do any input or output operations on it.  Opening
   a FIFO for reading normally blocks until some other process opens the
   same FIFO for writing, and vice versa.  See fifo(7) for nonblocking
   handling of FIFO special files.

注意:有两个重要细节:

1) the 'mode' parameter is modified by the value of 'umask'
2) both ends of the fifo must be open at the same time
   before any I/O operations can be performed.
相关问题