As everybody knows, execve()
system call replaces a calling process image with a new process image. At the same time the file descriptors table remains the same.
The idea of this example is to show how launched via execve()
processes can access file descriptors from their parent.
The parent process creates 4 pipes (unidirectional data flows) for stdin/stdout streams of its two children. Then the parent forks itself twice to spawn its children.
Each child process binds corresponding pipes to its stdin & stdout and then runs child
executable via execl()
. To simplify the example, child
processes also explicitly shares their stdin file descriptors between each other via command line argument. In the end parent is able to read from
children stdouts and write to their stdins, while children are able to write to sibling's stdins (see the schema below).
+------------+
| |
| |
| parent |
| |
| |
+---+----+---+
| |
| |
+------------+ stdin | | +------------+
| |<--------+----0--------| |
| | | | |
| child I | | | child II |
| | | stdin | |
| |--------------+------->| |
+------------+ +------------+
# compile parent
> cc parent.c -o parent
# compile child
> cc child.c -o child
# launch the example
> ./parent `pwd`/child
# expected output
> Parent started
> Parent forked first child
> Parent forked second child
> Message from parent has been written to first child stdin
> Message from parent has been written to second child stdin
> Child 1 STDOUT: echo from [first]: [message from parent]
> Child 2 STDOUT: echo from [second]: [message from parent]
> Child 1 STDOUT: echo from [first]: [message from second child]
> Child 2 STDOUT: echo from [second]: [message from first child]
> Parent finished
Do not forget to close file descriptors in forked processes before exec
uting ;-)