我不明白我做错了什么,请帮助我指出。我只是在这里输入我正试图在程序中做的事情,这样就容易理解了。我已经创建了3个命名管道,并将字符串"Hello, world!"写入第一个命名管道myfifo.example。现在我正在读取同一个命名管道并尝试将数据复制到第二个命名管道cmyfifo11。这种读写是不可能的。它甚至不打印行(1)和(2)。任何人都能纠正我吗。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<fcntl.h>
#include<string.h>

int main()
{
    int n, fd1, fd2;
    int pid,status;
    char    line[30]="Hello, world!\n";
    if (mkfifo("myfifo.example", 0660)<0)
        perror("Cannot create fifo");

    if (mkfifo("cmyfifo11", 0660)<0)
        perror("Cannot create fifo1");
    if (mkfifo("cmyfifo22", 0660)<0)
        perror("Cannot create fifo2");
    if((fd1= open("myfifo.example", O_RDWR))<0)
        perror("Cannot open fifo to write");

    if ( (pid = fork()) < 0)
        perror("fork error");
    else if(pid==0){
        int z=write(fd1,line,strlen(line));
        printf("Write is done on myfifo.example\n");
        printf("CHILD PROCESS 1\n");
        fd2=open("cmyfifo11",O_RDWR);
        printf("Value of fd2=%d\n",fd2);
        if(fd2<0)
            printf("Cannot open cmyfifo11\n");
        printf("Reading\n");
        if((n=read(fd1,line,z))<0) /* Read and write is not happening */
            perror("Read error");
        printf("Value of n:%d with line %s\n",n);--->(1)
            int x=write(fd2,line,n);-------------->(2)
            printf("%d\n",x);

    }

    else if(pid>0){ printf("Parent area with %d\n",getpid());sleep(300);}
    printf("Common area\n");

    return 0;
}

输出是
Write is done on myfifo.example
CHILD PROCESS 1
Value of fd2=4
Reading
Parent area with 349

最佳答案

您有一个分段错误,因为您忘记将line传递到printf()

printf("Value of n:%d with line %s\n",n)

应该是
printf("Value of n:%d with line %s\n",n, line);

关于c - mkfifo读写错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16648135/

10-12 00:52