Skip to content

Instantly share code, notes, and snippets.

@alirezaarzehgar
Created October 24, 2022 13:23
Show Gist options
  • Select an option

  • Save alirezaarzehgar/c79311faabfd74332deb1341b633d4cc to your computer and use it in GitHub Desktop.

Select an option

Save alirezaarzehgar/c79311faabfd74332deb1341b633d4cc to your computer and use it in GitHub Desktop.
Funny bugs cause problem on understanding `fork()` syscall :)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
printf("buffer:)) -> ");
/* Fix: `fflush(stdout);` */
for (size_t i = 0, p; i < 15; i++)
{
/* Fix: `if ((p = vfork()) == 0)` */
if ((p = fork()) == 0)
{
printf("pid : %d\n", p);
_exit(0);
}
}
for (size_t i = 0; i < 15; i++)
wait(NULL);
return (EXIT_SUCCESS);
}
/**
* output:
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> pid : 0
buffer:)) -> ⏎
*/
/**
* Why repeating show unprinted buffer each time ?
* Cause every process that created using fork syscall,
* make a copy of .text, .data, stack, descriptors and ... of parent.
*
* Every subprocess have a unflushed buffer copied from parent
* that should flushed.
*
* For fixing this problem you cah flush buffer before calling fork
* or using vfork instead of fork syscall to share memory between processes
* or using another ways that uses shared memory on multiple processes.
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment