簡體   English   中英

父進程不讀取表單管道

[英]Parent process doesn't read form pipe

我有這樣的事情:

pipe
close(pipe[0]);
parent writes something to pipe
close(pipe[1]);
fork();
if(child)
{
  close(pipe[1]);
  child reads from pipe
  close(pipe[0]);
  child does some operations
  child writes to pipe
  close(pipe[1]);
}
else
{
  back to parent
  close(pipe[0]);
  wait(&code);
  parent tries to read what the terminated child just wrote but fails to do so
}

我不知道如何讓父母從被終止的孩子那里讀書。 我需要使用dup嗎? 我不太確定dupdup2在什么情況下有用。

使用write()read()函數完成write()read()

我必須使用管道而不是fifo或其他方法在進程之間進行通信。

我認為你需要的是fifo套件,我認為你也不需要使用dup 這是一個有效的代碼:

#include <fcntl.h>
int main()
{
int e=open("fif",O_RDONLY|O_NONBLOCK);
if(fork()==0)
{
    int d=open("fif",O_WRONLY);
    write(d,"hi there\n",9);
    close(d);
    //sleep(5);
    exit(0);
}
wait();
char buf[15];
int n=read(e,buf,15);
buf[n]=0;
printf("%s", buf);
//wait();
return 0;
}

本文的一個示例說:

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

    main()
    {
            int     fd[2];
            pid_t   childpid;

            pipe(fd);

            if((childpid = fork()) == -1)
            {
                    perror("fork");
                    exit(1);
            }

            if(childpid == 0)
            {
                    /* Child process closes up input side of pipe */
                    close(fd[0]);
            }
            else
            {
                    /* Parent process closes up output side of pipe */
                    close(fd[1]);
            }
            .
            .
    }

IIRC就是這樣做的。 關鍵是關閉父子進程中未使用的fd。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM