父母如何选择与哪个分叉的子进程进行通信?

时间:2014-10-16 21:12:26

标签: process pipe fork

我从一个父进程创建了几个子进程,并且我还在每个进程和父进程之间创建了双向管道。现在的问题是如何在子进程和父进程之间来回做不同类型的工作,并让孩子与父进行通信?我正在考虑跟踪每个进程的PID,并将其用作身份切换。但从技术上讲,如何?附件是我到目前为止的代码。

struct val
{  int testInt;
  char testChar;
};

int main ()
{   val val1;
    pid_t cpid[3];
    int fd[2], fdd[2];
    int SFC;

for (int i=0; i<3; i++)
{   pipe(fd);
    pipe(fdd);

    cpid[i]=fork();
    if(cpid[i]==0)
    {   cout<<"\nI am a child and my pid is:"<<getpid();
        cout<<"\nMy parent is: "<<getppid();
        SFC=i;
        close(fd[1]);//close fd-pipe write end for child
        read(fd[0], &val1, sizeof(val1));//read from pipe
        close(fdd[0]);
        write(fdd[1], &SFC, sizeof(SFC));
        close(fd[0]);
        close(fdd[1]);

        cout<<"\nChild received value: "<<val1.testInt<<val1.testChar;
        cout<<"\nChild sent value: "<<SFC;
        cout<<endl;
        break;
    }
    else
    {   close(fd[0]);//parent close read end of pipe fd
        close(fdd[1]);//parent close write end of pipe fdd
        val1.testInt=4;
        val1.testChar='A';
        write(fd[1], &val1, sizeof(val1));//parent write to fd
        read(fdd[0], &SFC, sizeof(SFC));//parent read from fdd
        close(fd[1]);
        close(fdd[0]);

        wait(NULL);
        cout<<"\nI am the parent and I have this child: "<<cpid[i];
        cout<<"\nParent sent out value: "<<val1.testInt<<val1.testChar;
        cout<<"\nParent received value: "<<SFC<<endl;
    }       
}
return 0;

}

0 个答案:

没有答案