1

私は何が間違っているのか理解していません。親切に指摘してください。ここでは、理解しやすいように、プログラムで正確に実行しようとしていることを入力しています。"Hello, world!"3 つの名前付きパイプを作成し、最初の名前付きパイプに文字列を書き込みましたmyfifo.example。現在、同じ名前付きパイプを読み取り、データを 2 番目の名前付きパイプにコピーしようとしています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
4

1 に答える 1

1

You have a segmentation fault because you forgot to pass line to printf()

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

should be

printf("Value of n:%d with line %s\n",n, line);
于 2013-05-20T11:50:48.507 に答える