Learn and use fork(), vfork(), wait() and exec() system calls on Linux
linuxtechi.com
linuxtechi.com
shashi@linuxtechi ~}$ vim 1_fork.c
#include<stdio.h>
#include<unistd.h>
Int main(void)
{
printf("Before fork\n");
fork();
printf("after fork\n");
}
shashi@linuxtechi ~}$
shashi@linuxtechi ~}$ cc 1_fork.c
shashi@linuxtechi ~}$ ./a.out
Before fork
After fork
shashi@linuxtechi ~}$
How exactly is that demonstrating how fork() works? The article is completely missing any explanation - like why 'After fork' was only printed once and not twice as would be initially expected (It's unclear to me: while stdio buffering can cause strangeness if you don't flush buffers before a fork(), surely in this case both processes will exit cleanly and should flush their post-fork outputs?)My understanding is that `fork()` is a nice wrapper around `posix_spawn` and, in particular, `clone()`. And in some ways you're right: as an experienced developer I can really appreciate the extensibility of using `clone()` instead of `fork()`.
Unfortunately if I were to use `clone()` _ever_ then I would be immediately chastized by the architecture lead. He's not a C dude. I don't think he even understands the concept of programs sharing an address space (he's also anti-thread). All of it stems from "make programs simple" in an effort to minimize maintenance costs down the road. And in many ways he's right too. `clone()` is anything but simple despite being more extensible and `posix_spawn()` is just a more complex `fork()` in that regard.
Not really, you can't implement fork on top of POSIX spawn, but you can do the reverse. On linux they are both implemented on top of a lower lower level primitive (clone).
> I don't think he even understands the concept of programs sharing an address space (he's also anti-thread).
Personally, I find it easier to reason about than both the parent and the child having the same return stack but YMMV.
it's meant for cases where you want to avoid a bit of the fork overhead or if you need to spawn a subprocess from an existing memory-heavy process without getting a KILL from the kernel if overcommit is disabled (as the fork COW doubles your claim on memory even if you don't actually trigger a copy)
Unsurprisingly, that's also true for plain fork in a multithreaded program.
Basically everything from threads to program invocation is just this one powerful systemcall.
> If you use clone() you're on your own.
https://sourceware.org/bugzilla/show_bug.cgi?id=10311
Sometimes it feels like the standard library is holding C back. I wonder how many great Linux-specific features go unused because of it.
Highly recommend this book, its filled with fun tidbits of Linux-lore.
[0] https://www.amazon.com/Linux-Programming-Interface-System-Ha...