无法创建命名管道

时间:2014-06-26 19:46:25

标签: c linux named-pipes

我正在尝试制作一个在Linux下使用C语言的程序,这里是代码:

 #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中停止它返回一个否定的返回值?我不明白为什么?任何想法?

提前谢谢!

1 个答案:

答案 0 :(得分:2)

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

#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!后续调用可能会改变它。

相关问题