无法创建命名管道

标签 c linux named-pipes

我正在尝试在 Linux 下用 C 编写一个使用 FIFO 的程序,这里是代码:

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


#define TFIFO "tfifo"
#define BUFFLEN 100
#define MODE (S_IWUSR|S_IRUSR | S_IWGRP | S_IRGRP| S_IROTH|S_IWOTH)
int main (){

    pid_t npid;
    size_t anz;
    int fds;
    char* fifo_name = TFIFO;
    char msgbuf[BUFFLEN] ="\0";

    if( mkfifo(fifo_name,MODE)<0){
        printf(" Couldn't make the fifo \n");
        return -1;
    }
    npid = fork();

    if( npid > 0){
        printf( "Parent process \n");
        if((fds = open(fifo_name,O_WRONLY))== -1 ){
            printf(" Couldn't write in the fifo  \n" );
            return -1;
        }
        printf( " Parent Process:  waiting for the message  \n ");
        fflush(stdin);
        scanf("%[^\n]",msgbuf);
        anz = strlen(msgbuf)+1;
        write(fds,msgbuf,anz);
        printf(" Parent  process : EXIT \n ");

    }else {
        if(fds = open(fifo_name,O_RDONLY) ==-1){
            printf("Couldn't open the fifo for reading  \n");
            return -1 ;
        }
        printf(" Child process received :   \n  ");

        if(( anz = read(fds,msgbuf,sizeof(msgbuf)))!=-1){
            printf(" %s    \n",msgbuf);
            remove(fifo_name);
            printf(" Exit the child process \n");

        }
        else {
            printf( " DIGGA FATLAE ERROR  \n ");
        }

    }
}

当我运行 proram 时,它在 mkfifo 中停止,它返回一个负返回值 ??我不明白为什么?有什么想法吗?

提前致谢!

最佳答案

您可以通过这种方式获取错误编号:

#include <errno.h>
...
if (mkfifo(fifo_name, MODE) < 0) {
    printf("Couldn't make the fifo, error = %d\n", errno);
    return -1;
}

您还可以使用 strerror() 获取错误的文本描述。

#include <errno.h>
#include <string.h>
...
if (mkfifo(fifo_name, MODE) < 0) {
    printf("Couldn't make the fifo, %s\n", strerror(errno));
    return -1;
}

重要:总是在任何其他库调用之前阅读 errno!后续调用可能会更改它。

关于无法创建命名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24438950/

相关文章:

c++ - IDE/调试器的停止执行按钮

linux - 用于更新计算机之间文件差异的脚本

Linux $PATH 变量自动更新

linux - 'html.sty' 和 latex2e

c - C中的命名管道(FIFO)读取文件内容

.net - NamedpipeClientStream 无法连接,一直超时

c - Eclipse:无需在 Eclipse 中编译即可调试大型 C 项目

c - C 中的辛普森法则 - 错误答案

c - gdb 堆栈溢出

wcf - 写入管道 : Unrecognized error 232 (0xe8) 时出错