← Back to context

Comment by klodolph

4 years ago

fork + threads is not undefined behavior. It is safe as long as you only do “async-signal safe” functions in the child. The child will be single-threaded.

The Linux man pages have a list of safe operations after fork here: https://man7.org/linux/man-pages/man7/signal-safety.7.html

Note that this includes most of your standard syscalls, like (importantly) write(), read(), close(), chdir(), as well as certain “obviously safe” library functions like strlen(), memcpy(), etc.

Non-multithreaded programs can fork() how they like and do whatever they want after (mostly).

> fork + threads is not undefined behavior. It is safe as long as you only do “async-signal safe” functions in the child. The child will be single-threaded.

Yes, but the async-signal-safe restriction is pretty severe, so you have to know what you're doing. Yes, that's also true of vfork(), but at least vfork() will be much faster.

> Non-multithreaded programs can fork() how they like and do whatever they want after (mostly).

Only as long as they haven't used libraries that are not fork-safe prior to calling fork(). And you still need to do things like fflush() stdio handles prior to fork()ing.