Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when you create a pipe after a fork() command?

Tags:

c

Do you have two pipes then? And when the parent process writes something into the pipe can the child process read it?

What will be the difference if you create a pipe before the fork?

When I tryed it out it just messed up with my data I wantet to transfer from child to parent and I got some crzy symbols instead of an integer.

like image 495
nanobot Avatar asked Oct 23 '25 18:10

nanobot


1 Answers

If you create a pipe after a fork(), in both the child and parent process, you have two pipes - one in the child and one in the parent. Each process owns both ends of its respective pipe. Neither pipe is attached to both the child and parent process, and neither process will be able to communicate with the other via the pipe that it owns.

If you create a pipe before a fork(), on the other hand, there is only one pipe, and each process (parent and child) will have a file descriptor referring to each end of the pipe (because the child naturally inherits the file descriptors of the parent). In this situation the processes can communicate by writing to / reading from alternate ends of the pipe.

It is usual practice, if you want to create a pipe to communicate between a child and parent process, to create the pipe before the fork, and close one (different) end of the pipe in each process. Since pipes are generally unidirectional, this allows one-way communication between the processes. You can use a socket instead (via socketpair), or create two pipes (before forking), if you want bi-directional communication.

like image 157
davmac Avatar answered Oct 26 '25 07:10

davmac