1

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
3
  • I am not sure if this question is better suited for StackOverflow or Unix.SE. I thought that I would be most likely to find an answer here, but I may be wrong, in which case please indicate where is the best place to move the question. Thanks :)
    – rahmu
    Commented Jan 10, 2022 at 8:07
  • 2
    My guess would be that this is related to buffering of stdout. You could try to flush stdout before the fork to see if that changes the behavior.
    – rsp
    Commented Jan 10, 2022 at 12:20
  • @rsp I confirm that your suggestion seems to be correct. Good intuition.
    – rahmu
    Commented Jan 12, 2022 at 10:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.