简体   繁体   中英

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

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.

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() , there is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM