Punit Dhoot
Punit Dhoot

Reputation: 143

Better understanding of pipes

While learning about pipes, by mistake, I wrote the following code

int main()
{
    pid_t pid;
    int status;
    int p1[2];

    pid = fork();
    pipe(p1);

    if(pid==0)
    {
        dup(p1[0], 0);
        close(p1[1]);
        execv(abs_addr_of_some_bin , argv);
    }
    else
    {
        dup(p1[1] , 1);
        close(p1[0]);
        write(p1[1] , some_rand_text , size_of_text);
        wait(&status);
    }
}

The binary being executed has a read(0 , buf , size) statement, that reads from STDIN.

Well, the above code is obviously incorrect, as I have fork() before the pipe(). So when I try to output the buf in the other binary, it prints some random value that is different everytime I execute this file. What could be the reason behind this?

Also, if i correct my code (i.e call pipe() before fork()), there are certain things related to the working of the pipe that confuse me:

  1. As the p1 array will have different memory addresses for both processes( parent and child), how does the OS know that the other end of p1[0] (in the child) is p1[1] (in the parent)?

  2. What kind of memory operations take place in this process?

Thanks in advance!

Upvotes: 3

Views: 99

Answers (1)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36441

Do not create the pipe after the fork but before! If you create it after then you are creating two unrelated pipes... As you need to share the same pipe for both processes, create it before forking.

You have random values because your pipes are not connected and something didn't really test the reads in your execed process.

About addresses. No p1 has exactly the same address in the parent and the child! But these address are in different address spaces. Addresses a process manipulates are always relative to its given address space.

The fork duplicates address space of the parent process and built a strict copy of it for the child process.

Upvotes: 1

Related Questions