无法建立命名管道

无法建立命名管道

我试图在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!随后的通话可能会改变它。

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

10-12 01:03