0

子プロセスと親プロセスとのパイプ通信を試してみたい。親プロセスはパイプに書き込み、子プロセスはこれを読み取りますが、私のプログラムは「書き込み:壊れたパイプ」というエラーを受け取ります。このコードを変更するにはどうすればよいですか? ありがとう。

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <errno.h>
#include <fcntl.h>


int main(void)
{
    int i=0;
    int child=5;
    int fdp;
    int fds[2];
    int controlRead;
    int controlWrite;
    char pathName[30] = {"Trying Pipe Communication\n"};


    if(pipe(fds) < 0)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    do{

        if(child == 0)
        {
            close(fds[1]);
            if( (controlRead = read(fds[0],pathName,sizeof(pathName)) ) <= 0)
            {
                perror("read");
                exit(EXIT_FAILURE);
            }
            close(fds[0]);

            printf("boru :%s\n",pathName);
            wait();
        }
        else
        {

            printf("Parent process\n");
            close(fds[0]);
            if( (controlWrite = write(fds[1],&pathName,sizeof(pathName))) <= 0)
            {
                perror("write");
                exit(EXIT_FAILURE);
            }
            close(fds[1]);


        }
        i++;
        child = fork();
    }while(i<3);

    return 0;
}
4

2 に答える 2

1

読み取りループは、ソケットを閉じる前に読み取られたバイト数をカウントします。そうしないと、終了が早すぎます。

パイプはパケット転送ではなく、単一の読み取り/書き込みは実際には一連の操作です。したがって、配列を作成するときに、配列が 1 つになると想定するのは誤りです。

于 2013-04-21T22:58:58.643 に答える