10 ms·
Fork() without exec() is dangerous in large programs
- caf 10y agoIn my opinion, it's libraries that secretly use threads under the covers (but still access state shared with the rest of the program like the malloc heap) that are what's dangerous.
- Johnny_Brahms 10y agoguh. Those bugs aren't fun to hunt down. I don't think you really understand the importance of avoiding global or semi-global states until you have to do concurrent stuff, or when you have to start being serious about tests.
- pcwalton 10y agoI dunno--under that definition every concurrent GC is "dangerous".
- chubot 10y agoWhat libraries need to do GC? That is a language issue and not a library issue. When you are embedding a language like Go in a C program, its runtime becomes a library. But that's the example the proves the rule: there are (or were) well-known problems with that. Libraries shouldn't be doing GC.
- dozzie 10y ago> What libraries need to do GC? That is a language issue and not a library issue. Boehm GC disagrees.
- chubot 10y agoYes. Libraries should provide algorithms and data structures, and parameterize a threading interface if necessary (though I think it's usually not necessary). Applications can then instantiate their own threads and pass them to the library (i.e. dependency injection.) So if you have 10 different concurrent libraries in an application, then you don't end up with 10 different threading paradigms or 10 different thread pools. This is a matter of application architecture -- libraries shouldn't bake in a specific policy.
- TickleSteve 10y agotrue... ...this applies not just to threading, but other things that are not in the domain of the library such as memory allocation strategy or communication mechanism. Libraries should be small, focused and decoupled. This is the way to proper re-usability.
- amag 10y agoLike left-pad?
- TickleSteve 10y agojeez, no.... extremes of everything are terrible. I suppose another rule should be that there libraries should encapsulate a sufficient amount of complexity to make their existence worthwhile.... unlike left-pad.
- gnaritas 10y agoThat's a function deployed as a library, not a real library; the word library implies many functions.
- prodigal_erik 10y agoThere's nothing really wrong with packaging small isolated pieces of code. The debacle came from consumers' bad habit of randomly upgrading their dependencies without doing full regression testing (partly because the tooling encourages this terrible practice).
- djsumdog 10y agoI know it's very different in JVM land, but many Akka libraries do something similar where they take am actor system, allowing the developer to share or separate the actor systems.
- rlpb 10y ago> Threads are inherently the right way to do concurrency for more complex tasks. True, but they're more often used as a crutch where a select-style loop and/or state machine would be more suitable, leaving race conditions in their wake.
- eridius 10y agoI completely disagree. The only part of this that seems dangerous is the fact that it can turn a single-threaded program into a multi-threaded one, and the only real problem there is it makes fork-without-exec unsafe. But fork-without-exec is basically unsafe anyway unless you can absolutely guarantee that nothing has ever spawned a thread. Meanwhile, preventing libraries from using threading under the covers basically means throwing away lot of performance gains for no good reason.
- adrianratnapala 10y agoThis is the very first time I have heard about fork-without-exec as dangerous, but it is not the first time I have heard about having to be careful about libraries and hidden threads. The thing is that any thread you launch is a big piece of machinery and your attempt to hide it is inevitably going to be a leaky abstraction.
- eridius 10y ago> The thing is that any thread you launch is a big piece of machinery and your attempt to hide it is inevitably going to be a leaky abstraction. That's not true at all. Threads aren't that complicated, and there's lots of ways of using them that aren't complicated and don't leak anything. As a trivial example, if I want to process a bunch of data, it might be faster to process it in parallel, and I can use a thread to do that without causing any observable difference in behavior (beyond potentially turning a single-threaded program into a multithreaded one). And if I'm on a platform like OS X or iOS, I can use higher-level threading APIs like libdispatch that make it even simpler.
- adrianratnapala 10y agoThis is exaclty the kind of reasoning that makes library writers stumpble into using abstractions that turn out leaky. The whole point of the OP is to show one (of many) machanisms through which it does cause an observable change in behaviour. And your example of a big calculation in a library is particurly bad, because the user can threadify that herself if she wants to. #include <thread.h> #include <yourlib.h> #include "my_eventloop.h" void launch_da_ting() { std::thread ting_doer([]{ Result rez = yourlib::do_da_ting(); my_event_loop::post([rez](){get_rez(rez);}); }); ting_doer.detach(); } Now it's true those five lines would become a single function call if your library forced the user to user a particular dispatching library. But I think that would be poor seperation of concerns.
- pjmlp 10y agoWhat is dangerous is that the interactions between threads and processes aren't part of POSIX standard and its behavior is OS specific across UNIX implementations. This isn't an issue on non-UNIX OSes.
- wruza 10y agoHow many non-unixes do have fork_without_exec()?
- pjmlp 10y agoMost non-UNIX OSes only have exec(), not fork(). Hence why fork() is just kind-of implemented on their POSIX compatibility layers. In UNIX it is only an issue, because IEEE doesn't want to set in stone in POSIX how threads, signals and processes should interact, due to the way threads were added to UNIX.
- cperciva 10y agoNon-unix systems don't have exec; they have spawn.
- the_mitsuhiko 10y agoWindows has exec.
- wruza 10y agoExec is substitution of current process with new image without closing fds or changing pid. Which winapi function does that?
- the_mitsuhiko 10y ago_wexec and friends. It internally uses CreateProcess obviously.
- 10y ago
- the_mitsuhiko 10y agoLibraries should not be disallowed from spawning threads. Threads are inherently the right way to do concurrency for more complex tasks. fork() is a tremendously complex call and has huge implications on all things in the OS. For many years now I have the rule that new code must not use fork() and I am living a happier life. It's a bad call and it has no use if you have good threading support in the language. There are many programming languages that do not support fork() andy more or heavily restrict the use.
- DSMan195276 10y agoI would add, in many/most cases using fork() without calling exec() just doesn't make sense. Even at the system call level you have clone(), which is how actual threading is implemented under the covers. And really, if you need a thread, just get a thread. I see extremely few or no advantages to doing fork() instead of spawning a new thread normally using whatever interface is provided (except in the case of exec() where fork() or vfork() is necessary).
- xroche 10y agofork() is not per se "dangerous" in such context. You just have to be careful enough and only use asynchronous-signal-safe fonctions, as you would do in a signal handler (see https://www.securecoding.cert.org/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers https://www.securecoding.cert.org/confluence/display/c/SIG30...) Typically calls such as malloc(), printf() etc. are strictly forbidden in the child after a fork().
- ej_campbell 10y agoOnly if your app is multi-threaded. Unfortunately, many apps are multi-threaded "under the covers" due to libraries that spawn threads, so you need to be careful. This post does the best job explaining the issue: http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them http://www.linuxprogrammingblog.com/threads-and-fork-think-t...
- evanj 10y agoThis is possible, but I find these restrictions to be hard to follow. As soon as you need to call a function, you now need to audit that function to determine that it only calls other async signal safe functions. When you come back to the code to fix a bug six months later, you need to remember these restrictions. Do this when you must, but it is easy to screw up.
- rdtsc 10y agoYap. Erlang 19 (latest version) switched to using a smaller spawner executable and spawns all OS processes from there by forking. So it forks something restricted and small not the whole VM. Here are the details of how it works: https://github.com/erlang/otp/blob/a5256e5221aff30f6d2cc7fab4875914ae734217/erts/emulator/sys/unix/erl_child_setup.c#L21-L49 https://github.com/erlang/otp/blob/a5256e5221aff30f6d2cc7fab... They also claim a 3-5x speedup for launching external commands because of it. So there is a nice performance boost as well. So basically can add 4th strategy -- fork once a small program at the start, then fork from there from then on.
- xroche 10y agoThis is not a bad strategy, especially because between the moment you fork() and the child calls exec(), you have a lot of memory regions shared in copy-on-write (because it would be Too costly to actually duplicate the universelle). Which means that busy threads writing in memory in the parent area will trigger minor page faults, possibly impacting performances...
- ithkuil 10y agoyeah, that's why vfork has been introduced back in the days. See http://man7.org/linux/man-pages/man2/vfork.2.html http://man7.org/linux/man-pages/man2/vfork.2.html
- the_why_of_y 10y agoThe "historic description" in the man page you cite disagrees: vfork(2) was added before BSD had copy-on-write, so the memory was actually copied and vfork(2) is essentially a crude hack to avoid that. Unfortunately once copy-on-write was implemented, the crude hack was retained for backwards compatibility....
- evanj 10y agoThanks for pointing this out! Interesting that the code states that part of the concern is increasing memory usage. I don't quite understand why it would "duplicate the memory usage" since fork uses copy-on-write? Anyway, I didn't explain it well, but this was what I was trying to get at with "fork a worker at the beginning of your program, before there can be other threads."
- ambrop7 10y agoThe fork-exec code in my program currently does some things that are supposedly unsafe, but I can't figure what to use instead of initgroups() which is not async-signal-safe. I want to run the child as a different user for which I do initgroups+setgid+setuid between fork and exec. The only solution I see is to run getgrouplist() before the fork then in the child use setgroups() instead of initgroups(), but both of these functions are non-standard. EDIT: Never mind, seems like initgroups() is also nonstandard but generally available on Unix-like systems.
- saynsedit 10y agoFace the fact, fork() is fundamentally flawed!
- ahoka 10y agoI would like to see the reasons this comment was down-voted. It is true that fork(2) is simple and elegant design, but it involves a huge accidental complexity and hidden implications like in the original article. There is a reason that Linux has clone(2) underneath.
- astrodust 10y agoEvery method has limitations. If you want to call these flaws that's just semantics.
- the_mitsuhiko 10y ago> It is true that fork(2) is simple and elegant design What exactly is simple and elegant about it? Have you looked into how much tooling is necessary everywhere in unix to make it work? It's insane. It has a huge footprint and it does not provide standardized APIs to make it work for non covered cases (the best we have is pthread_atfork which is not portable).
- qznc 10y agoFork is simple, but not easy.
- the_mitsuhiko 10y agoWhat makes for simple? I really need to understand this. I implemented fork many years ago for a university operating system and nothing about either the implementation nor the usage is simple. I use fork on a daily basis and the POSIX version of it is insanely complex for everybody involved.
- qznc 10y ago
- lsiebert 10y agoIf there are specific issues with locks from dead child processes that deadlock, maybe the locks could be addressed specifically.
- datenwolf 10y agoHmm, consider we'd want to keep fork(), then the only safe way to deal with this would be, that critical sections were actually transactions implemented on the OS level and at after fork() in the child all transactions in flight get rolled back before returning from fork(). I see two implementation challenges with that suggestion: 1.) implementing that transaction mechanism as a kernel feature: When entering a CS mark all pages CoW, upon leaving the CS merge modified pages (problem: Whole pages are then mutual exclusive, dealing with this is the challenge) 2.) battling with user space implemented locks that use atomics. ----- An immediate mitigation I see is, that fork() itself is a CS on _all_ the locks of a process. If we consider that only the standard locking mechanisms are used, then whenever a CS is entered (which includes the creation process of a locking primitive) it raises/posts a global fork-lock semaphore. And upon leaving that semaphore is lowered. This still leaves the DIY-locking primitives problem open. But it should be more or less straightforward to add this to the system libc/pthread libraries' locking primitive implementation and fork() syscall wrappers. Or did I miss something essential here? Talk is cheap, so if nobody has any obvious objections I'd actually go ahead implement it. EDIT: Okay, one immediate problem I see is, that this would pose a challenge for calling fork inside a CS. Technically this is a situation where thread recursive locks would help, but as we all know, recursive locks are highly problematic.
- the_why_of_y 10y agoSounds like you are trying to re-invent Software Transactional Memory - was a nice idea 10 years ago, but after lots of research it is still not available in common runtimes... Some more problems to consider: 1. how do you roll back IO that happens in a critical section? 2. your global semaphore will be highly contended and basically destroy scalability
- datenwolf 10y agore 1) good point, didn't think of that re 2) the fork global lock satisfies every requirement for a multiple-readers/single-writer, with fork() being the only writer. Unless the program does a lot of fork()-ing it should hardly ever run into contention. The moment fork() waits on the lock, further attempts on read-lock are delayed until after fork() completes and the existing reads are waited for, before fork()-ing.
- antirez 10y agoIf you are in control of all the threads that an application is running, you can call fork() safely by making sure the threads are put in a safe state (no critical locks retained) when the fork() call happens. Also note that many things that should normally be unsafe, like having running threads calling malloc() while another thread is forking, are actually safe in the real world using certain implementation of fork, since there are pre/post fork "hooks" in the malloc implementation in order to fix the state of the child. So if you control very closely the libs you link with and what they do, as well as the threads you use yourself, it is possible to use fork() in a reliable way.
- deleted 10y ago[deleted]
- deleted 10y ago[deleted]
- tankenmate 10y agoglibc attempts this using the pthread_atfork() hook. it takes the global malloc (and possibly other) forks in the parent before forking, then both the parent and child release the lock before returning to the callee's code. obviously if you have locks in your own code then you may or may not need to hold these before calling fork() so that both parent and child can release them after the fork(). the apple way of just throwing its hands in the air and abort()ing sound either like giving up because the apple devs think it is too hard, or because they feel the need to impose their way in crippling code that uses fork() without calling exec() in my opinion if you are going to write a library that uses threads and is supposed to be thread safe then remember you need to handle the issue of fork(); don't be lazy, do the job properly, even if doing it right it is hard and ugly.
- evanj 10y agoYou are completely correct! The thing that surprised me is how difficult that can be. For example, on Mac OS X if you want to read the system proxy settings, you magically get threads added to your program that you can't control.
- kostyash 10y agoIt sounds like if you use threads and fork it might be a disaster. Its true, but the author blames only fork and skip the second part of the problem, threads. This is not fair, because fork is much older than POSIX threads. In fact, POSIX threads were poorly designed to use with fork.
- evanj 10y agoFair point. My opinion is that in today's age of multi-core CPUs, shared memory concurrency is extremely useful for making efficient use of computing resources. As a result, I find threads to be unavoidable in most large systems I've dealt with recently.
- kostyash 10y agoAgree, that multi-threading probably the best choice for CPU-intensive applications. But for databases or http-servers multi-process + coroutines/fibers can be a better solution. For example, Redis is few-thread application. It creates additional threads only for disk I/O, because unfortunately file descriptors in Linux/UNIX do not work in async mode. Btw, Redis reminds me, one really awesome usage of fork. To make a snapshot of itself Redis forks the main process. After that the child simply goes through tuples and write them to a files with out any worries that somebody will modify a records. Copy-on-write mechanism simply prevents it. Redis save snapshot code: https://github.com/antirez/redis/blob/unstable/src/rdb.c#L996 https://github.com/antirez/redis/blob/unstable/src/rdb.c#L99...
- hyperbovine 10y agoI ran into this exact problem recently in a multithreaded Python app and spent two days trying to figure out wtf was going on. The multiprocessing spawn startup mode that was added in 3.4 solves this for most use cases at the expense of a small performance hit. For 2.x you are SOL however.
- evanj 10y agoPart of my motivation for writing these things is because after I've wasted so much time, I'd love to help others not do the same. Hopefully the article shows up when you search for the right error message. Its also so I remember what the heck was happening. Re: multiprocessing in 3.4: I think it is unfortunate that due to backwards compatibility, the "forkserver" mode can't become the default on Unix, since it would help avoid this particular issue.
- zzzcpan 10y ago> How to use fork safely: 1. Only use fork to immediately call exec. 2. Fork a worker at the beginning of your program, before there can be other threads. 3. Only use fork in toy programs. 4. Stop writing broken multithreaded code altogether or if you must at least run an event loop per core/thread and use a wrapper for fork() to put the system into a fork()able state before forking. It's nice and reliable. Multithreading by itself is just not a high-level concept to be used reliably by programs.
- evanj 10y agoYou are completely correct: it is in fact possible to use fork if you can carefully control the state of threads in your program. My point is that can be difficult in large software projects, particularly when random APIs like "get the system proxy settings" use threads without you having any ability to control them.
- valarauca1 10y agoFork/Exec is only good if you are going to run a different program then you are currently executing. If you want a series of worker threads that are effectively the same as the master/initial thread. The proper way to do this clone(2) not fork, or fork/exec. When used properly clone allows your group of threads to share a single PID, and TGID (Thread Group IDentifier). This cuts down on kernel resources your process(es) are using. They can natively share file descriptors and memory between each other (improving cache coherence). Also their signals are handled globally for all threads at once, not each thread managing it's own signals like Fork/Exec will result in.
- stsp 10y ago$ man 2 clone man: No entry for clone in the manual.
- qwertyuiop924 10y ago...And why would you want that? The advantage for fork(2) over clone is that you CAN'T share those datastructures, making it harder to write code resulting a deadlock: you have to share explicitely. As for the kernel resources for the process, you'd be surprised how large RAM has gotten these days...
- qwertyuiop924 10y agoIn some programs, fork(2) is the right way to do concurrency. It's simple (API-wise), and it makes IPC explicit, as opposed to the implicit IPC of threads. clone isn't posix, so you can forget it, if you don't feel like being behind systemd in the "screw any system that isn't Linux" line. In places where you need the speed, threads are useful, but they're harder to use than forks. Annoyingly, threads and forks don't work well together. zzzcpan already talked about how to fork threaded code. As for the problem of libraries using threads, if a library you're using is using threads, and it's documented (it probably is), and you didn't know about it, I'll pencil that in as your fault. Other comments in this thread have dismissed fork(2) as a bad job entirely, but I don't think I agree. It's an effective way to do simple multiprocessing, and it's a lot simpler than threads in many contexts.
- known 10y agohttps://en.wikipedia.org/wiki/Thrashing_(computer_science) https://en.wikipedia.org/wiki/Thrashing_(computer_science)
- ahh 10y agoEndorsed. Even fork _with_ exec can be real trouble. This is one of my bugaboos at work: due to poor life choices and high pain tolerance, I own the infrastructure we use to spawn subprocesses (carefully.) For various reasons (security most notably) we have to do some very tricky things in and to the forked child before exec(), and pretty much all of this code is a disaster waiting to happen. Every so often I get feature requests for more stupid pet tricks people would like out of subprocesses, and they're always surprised by what their "simple" change would entail. I'd like it if Linux had native support for posix_spawn, but even that would require a lot of extensions to be useful. Don't get me started on the teams that want to break forking rules and thus ask me how to guarantee a process has no non-main threads. There are few ways you can make me more upset than by building software that breaks if some one else happens to call pthread_create and doesn't tell you.