首页 > 解决方案 > 将随机生成的值从子进程发送到父进程

问题描述

我已经编写了一个代码,它使用 rand() 在子进程中生成一个随机数...我需要使用 pipe() 将此随机值发送到父进程。当我使用 read() 和 write() 时,父级收到的值是 0 而不是随机数。

我没有收到任何错误,只是输出是收到的值是:0。

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<fcntl.h>


int main ()
{

    pid_t Cpid;
    int fd[2];  

    int rVal;



    //pid will store the value of fork()
    Cpid = fork();
    pipe(fd);       

    if( Cpid == 0) 
    {

        //CHILD
        rVal = rand()%100;
    ;
//this is in child process
    close (fd[0]);
    rVal = rand()%100;
    write(fd[1], &rVal,sizeof (rVal));
    close (fd[1]);

        printf(" Child Pid : %d sending random value : %d to parent : %d\n", 
    getpid(), rVal, getppid());


    }


    else if(Cpid != 0 )
    {

        printf (" Parent PID : %d\n", getpid());
        //this is the parent process
        close(fd[1]);
        read(fd[0], &rVal, sizeof(rVal));
        printf(" value recieved is : %d\n", rVal);
        close(fd[0]);
        printf(" value recieved by parent : %d\n", rVal);

    }



    return 0;


}

标签: cpipe

解决方案


代码应在分叉子代之前设置管道。否则,父母和孩子将使用不同的管道,并且将无法相互交谈。

int main ()
{

    pid_t Cpid;
    int fd[2];  

    // Create the pipe BEFORE forking.
    pipe(fd);       

    //pid will store the value of fork()
    Cpid = fork();

    if( Cpid == 0) 
        .. REST OF CODE ~~~

推荐阅读