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

Time:05-29

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

**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.

CodePudding user response:

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.

CodePudding user response:

As drorfromthenegev suggest problem is arising due to I am calling pipe() after fork().

So I call pipe() first and the i call fork() and it works..

Workable solution

#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;
    
    if(pipe(fd) == -1)//fd[0] for read fd[1] for write
    {
        perror("pipe");
        exit(1);
    }
    pid = fork();
    if (pid < 0)
    {
        perror("fork");
        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");
    }
}
  • Related