Consider the following C code:
#include <stdio.h>
#include <unistd.h>
int main() {
printf("PID: %d\n", getpid());
fork();
}
This should output the PID of the process and then fork a clone. When trying from a shell, this behaves in the expected way:
$ ./a.out
PID: 380
However if I execute this from within emacs using shell-command
(M-!
), the output is now different:
PID: 382
PID: 382
If I modify the program a bit:
#include <stdio.h>
#include <unistd.h>
int main() {
printf("PID-pre: %d\n", getpid());
fork();
printf("PID-post: %d\n", getpid());
}
I can see the proper output in an external terminal:
PID-pre: 398
PID-post: 398
PID-post: 399
However, again the shell-command executes the pre-fork printf twice:
PID-pre: 402
PID-post: 402
PID-pre: 402
PID-post: 403
How come shell-command
executes the whole process twice when using fork
? Is this the intended behavior? How can I work around it?
My system:
- OS: Fedora 35
- kernel: Linux fedora 5.15.12-200.fc35.x86_64
- lib C: GNU libc 2.34
- emacs: GNU Emacs 27.2 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.30) of 2021-09-25