我有两个不同的程序,我想通过一个fifo连接,由于某种原因,它不能正常工作。对mkfifo的调用返回-1,这意味着有些事情不正常。为什么mkfifo会失败?
这是我的代码:

int main(){

    pid_t pid;
    int rv;
    int fd;

    int fifonum;
    char *fifoName = "toServer2";
    fifonum = mkfifo(fifoName, 0666);

    if (fifonum<0){
        printf("\n unable to create a fifo\n");
        exit(-1);
    }

    fd = open(fifoName, O_WRONLY);

    if( (pid=fork()) == -1 )
    {
        printf("fork error, exiting\n");
        exit(1);
    }

    if(pid){

        printf("this is the parent\n");
        write(fd, "1", sizeof(int));
        close(fd);
        wait(&rv);
        printf("child exited with this status %d\n", rv);

    }else{
        printf("this is the child");
        if(execl("child", "child", NULL)==-1){
            printf("execl error");
            exit(1);
        }
    }
    return 0;
}

最佳答案

如果文件已经存在,mkfifo函数将失败。避免此问题的一种方法是在调用mkfifo之前删除文件。这样你就可以在每次运行程序时使用一个全新的空fifo。
一般的想法是调用stat看看FIFO文件是否存在,如果存在的话,用“cc>”删除文件,然后调用unlink以生成一个新的FIFO。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>

int createNewFifo( const char *fifoName )
{
    struct stat stats;
    if ( stat( fifoName, &stats ) < 0 )
    {
        if ( errno != ENOENT )          // ENOENT is ok, since we intend to delete the file anyways
        {
            perror( "stat failed" );    // any other error is a problem
            return( -1 );
        }
    }
    else                                // stat succeeded, so the file exists
    {
        if ( unlink( fifoName ) < 0 )   // attempt to delete the file
        {
            perror( "unlink failed" );  // the most likely error is EBUSY, indicating that some other process is using the file
            return( -1 );
        }
    }

    if ( mkfifo( fifoName, 0666 ) < 0 ) // attempt to create a brand new FIFO
    {
        perror( "mkfifo failed" );
        return( -1 );
    }

    return( 0 );
}

int main( void )
{
    if ( createNewFifo( "toServer2" ) < 0 )
        exit( 1 );

    // do something with the fifo ...
}

关于c - Linux C编程fifo无故失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28222561/

10-15 13:30