Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to communicate between child process and parent process but it is not working .
The child function only executing and not going into the parent function

What I have tried:

C++
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int main(int argc, char const *argv[])
{
    int _pipe[2];
    char arr[30];
    int pid;

    pipe(_pipe);

    pid=fork();

    if(pid==0)
    {
        while(1)
        {
            write(_pipe[1],"Hello world",100);
            printf("child process\n");
            sleep(1);
        }
    }
    else if(pid>0)
    {
        wait(NULL);
        while(1)
        {
             printf("parent process\n");
            read(_pipe[0],arr,sizeof(arr));
            printf("%s",arr);
            sleep(1);
        }
    }

    
    return 0;
}
Posted
Updated 26-Jun-18 22:04pm
Comments
Richard MacCutchan 27-Jun-18 3:56am    
Do you see any output from the parent process?

That is sourced by calling wait(2) - Linux manual page[^] and having an infinite while loop in your child process. The wait() call will block the parent until the child terminates or stopps / resumes by a signal. But that never happens in your code.

Note also that the unused side of a pipe should be closed and you are sending junk data which are never received (you are sending 100 bytes but receive only 30). Send only the number of bytes that are necessary (string length plus one here) and use a receive buffer that is large enough to hold the max. number of bytes that might be send.

See also 6.2.2 Creating Pipes in C[^].
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900