I have the following code written in C, taken from https://beej.us/guide/bgipc/html/multi/pipes.html:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
execlp("/bin/ls", "ls", NULL);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
execlp("/usr/bin/wc", "wc", "-l", NULL);
}
return 0;
}
When compiling and running this code in the terminal using strace I get the following output:
execve("./forks", ["./forks"], [/* 55 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f2b0e498700) = 0
pipe([3, 4]) = 0
clone(Process 7304 attached
child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2b0e4989d0) = 7304
[pid 7303] execve("/usr/bin/wc", ["wc", "-l"], [/* 55 vars */] <unfinished ...>
[pid 7304] execve("/bin/ls", ["ls"], [/* 55 vars */] <unfinished ...>
[pid 7303] <... execve resumed> ) = 0
[pid 7304] <... execve resumed> ) = 0
[pid 7303] arch_prctl(ARCH_SET_FS, 0x7f558acde700) = 0
[pid 7304] arch_prctl(ARCH_SET_FS, 0x7f4bef4f67c0) = 0
[pid 7304] exit_group(0) = ?
Process 7304 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
21
exit_group(0)
Can anybody explain, line by line, what is going on in the strace output? I've attempted to research how to interpret strace outputs but haven't had any luck.
Thanks in advance.
The shell calls
execve
with your executable and./forks
asargv[0]
. The/* 55 vars */
are the environment variables inherited from the shell.Probably sets up thread local storage for the newly launched process.
The
pipe
system call returns a pair of descriptors,3
and4
. The numbers are such because no descriptors other than0
(stdin),1
(stdout) and2
(stderr) have been allocated so far to the process.The
clone
system call corresponds to the call tofork
, spawning a new process. Even thoughfork
is commonly referred to as a system call, particularly on Linux it wraps a call toclone(2)
.Within the parent and the child, two new executables are started. The child exits with
[pid 7304] exit_group(0)
and the parent immediately receives aSIGCHLD
signal that a child process has changed its state.