Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix data write or read using pipe in c program is giving wrong output?

I am trying to get an integer input in the child process and send it to the parent process using pipe()

but I receive garbage values every time in the parent process.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
    pid_t pid;
    int fd[2];
    char *args[] = {"", NULL};
    int cnum,pnum;
    
    pid = fork();
    if (pid < 0)
    {
        perror("fork");
        exit(1);
    }
    if(pipe(fd) == -1)//fd[0] for read fd[1] for write
    {
        perror("pipe");
        exit(1);
    }
    if(pid == 0)
    {
        close(fd[0]);
        printf("\n**In the child process**\n");
        printf("Enter Number : ");
        scanf("%d",&cnum);
        write(fd[1],&cnum,sizeof(int));
        close(fd[1]);

    }
    else
    {
        wait(NULL);
        close(fd[1]);
        printf("\n**In the parent precess**\n");
        read(fd[0],&pnum,sizeof(int));
        close(fd[0]);
        
        printf("Number recieved = %d\n",pnum);
        printf("PID = %d\n", getpid());
        execv("./sayHello", args);
        printf("Error");
    }
}

Output of the above code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

**In the child process**
Enter Number : 212
**In the parent precess**
Number recieved = 1036468968
PID = 22528
Hillo Amol
PID = 22528

I give input of 212 but in parent 1036468968 received.

>Solution :

You call fork before you create the pipe FDs. After you call fork, the parent and the child both create their own pair of pipe FDs, and there’s no shared pipe between them.

Create the pipe before you fork and it could work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading