11 ms·
Fork() can fail: this is important (2014)
- abhisuri97 7y ago> If a function be advertised to return an error code in the event of difficulties, thou shalt check for that code, yea, even though the checks triple the size of thy code and produce aches in thy typing fingers, for if thou thinkest ``it cannot happen to me'', the gods shall surely punish thee for thy arrogance. http://www.lysator.liu.se/c/ten-commandments.html http://www.lysator.liu.se/c/ten-commandments.html
- usefulcat 7y agoWhen I first learned of this behavior, I immediately replaced all calls to fork() with calls to the following throughout our entire codebase: int checked_fork() { const int pid = fork(); if (pid < 0) { throw std::runtime_error("fork failed"); } return pid; }
- thestoicattack 7y agoDid you detect any crashes after the change?
- bluejekyll 7y agoThis is why separating return values from error codes is important. For example, in Rust, you’d never get into this situation, because a decent fork ffi function would immediately convert -1 into a Result carrying an error, and properly check errno. Java and C++ would throw an exception, etc. Thus preventing all sorts of bad behavior up the stack.
- jacobush 7y agoYeah, but in C++ you get people ignoring exceptions too. I'm fine with return codes, I don't mind them even though exceptions are maybe a little bit better.
- swsieber 7y agoTrue, but in this case, ignoring an exception would be better than ignoring a return code, right? It prevent you from accidentally sending a signal to -1 (e.g. all the processes you can). The danger here with the return code is that the return code value is a valid (but not intended) input to another function that normally uses the normal return value.
- jacobush 7y agoTrue, I guess just this example didn't jive with me. I'd never dream of ignoring the return code of fork(). Some other call I don't respect enough would probably bite my ass, though.
- oconnor663 7y agoIt's not just a question of whether you did the right thing when you wrote the code. Code gets refactored and moved around, maybe by people less experienced than the original author, or maybe just by the original author when they're tired or after they've forgotten the context. Wrapper functions get defined, libraries get updated, and support gets added for new platforms. Each of those changes is an opportunity to accidentally stop checking the return code.
- 7y ago
- vortico 7y agoProgramming is easy. Read the documentation for all functions you call. Make no assumptions. Read the RETURN VALUE section of man pages. Read about the behavior of NULL arguments. Don't do anything outside of the function "contract". This applies to anything from C to Rust to Javascript. If you break these rules, programming is hard. Working with programmers who make unproven assumptions is also hard. Either don't hire them, or train that behavior.
- noelwelsh 7y agoThis is just arrogant nonsense. If your attitude was followed in aviation safety passenger jets would still be crashing at a regular rate. Computers are good at following rules every time; humans are not. The systems should be designed so that the complementary strengths of each are used. This is one of the ideas behind types in programming languages: they provide checks that the computer (which is good at this task) performs every time you compile code. Put more simply, get rid of null from your programming language and you get rid of a whole class of errors.
- Out_of_Characte 7y agoYou're following up on his comment proposing strict adherence to rules by proposing a strict type system that isn't allowed to be violated. Which one is it? Are all errors supposed to be caught by the programmer? are all incorrect type conversions supposed to be caught? or are you saying that's nonsense and you shouldn't always adhere to these rules? Finally, NULL values are perfectly reasonable in programming. shifting them to another arbitrary number doesn't solve anything.
- noelwelsh 7y agoYou misunderstood the point. Computers are good at following rules and humans are not, so get the computers to do the rule following. That's what a type system is: a bunch of rules that the computer checks every time you compile your code. (As for null values, modern type systems have no need for them. I guess you aren't familiar with them, because the alternative is not "shifting them to another arbitrary number". Checking out Rust / Haskell / Scala / Reason / Elm etc. might help.)
- dooglius 7y agoPosts like this always perplex me, the behavior is clearly documented in the man page and clearly indicated by example demonstration code (e.g. [0]), so how could someone fall under the impression that this wasn't the case? [0] https://en.wikipedia.org/wiki/Fork_(system_call) https://en.wikipedia.org/wiki/Fork_(system_call)
- xeromal 7y agoPSAs don't hurt anyone and might help one who happened to miss it.Do you see anything negative with the post?
- dooglius 7y agoI don't have a problem with the post, I'm just wondering how one gets into a situation where it needs to be said.
- chousuke 7y agoI think the actual problem here is that fork has a bad API that is easy to misuse accidentally; and when something can go wrong, it eventually will go wrong. Raising awareness about bad APIs will also help people realize when they're about to create one themselves, which might cause them to switch designs.
- ColanR 7y agoFork has an extremely standard API, and that's a good thing. What needs to be quantified is how much ignorance a programmer can be expected to have, before errors they make are their own responsibility.
- chousuke 7y agoThe API being "standard" doesn't change it being bad. I mean, it is what it is and probably couldn't have been much better given historical reasons, but I think it's still useful to think on how it fails and how to improve on it.
- izabera 7y agoI like to use this construct: pid_t pid = fork(); switch (pid) { case -1: error case 0: child default: parent }
- OskarS 7y agoI did not know any of this, and now suddenly I have the overwhelming urge to type this into a terminal and see what happens: kill -KILL -1 But I'm going to restrain myself :)
- AdamJacobMuller 7y ago> If pid equals -1, then sig is sent to every process for which the calling process has permission to send signals, except for process 1 (init) Has this behavior with init always been this way? I could swear in the past that `kill -9 -1` used to kill init too (and thus cause a reboot), it was one of my favorite "fuck it and reboot" methods.
- pwinnski 7y agoI've used `kill -9 1` to reboot on a single-user system. Perhaps that is what you're remembering?
- AdamJacobMuller 7y agosingle-user when its in like another runlevel?
- aaronmdjones 7y agoLinux will not let you send a signal to init that it has not installed a signal handler for (to avoid unexpected terminate-by-default signals wrecking your machine), and no process can install a signal handler for SIGKILL; ergo, you cannot SIGKILL init. Other operating systems may vary, of course.
- deleted 7y ago[deleted]
- JoeAltmaier 7y agoFolks wonder why not every error code is checked. My friend Mike Rowe said it this way: it's like having an altimeter in your car. So if you drive off a cliff, you know how far it is to the ground.
- tedunangst 7y agoThat seems like a really dumb analogy in this context. Calling kill(-1) is not the only possible response to fork() failing.
- korethr 7y agoNot only is that a dumb analogy in this context, it's a plain dumb analogy. That's not how an altimeter works. Not only would you need an altimeter, but also fast and accurate GPS positioning, and current topographical maps of your area in order to know how far it is to the ground below that cliff.
- thedance 7y agoHonestly, it might be better if the system has run out of PIDs that a process fails to fork and kills a lot of other processes.
- peterwwillis 7y agoEverything can fail. Things can fail without even telling you they failed. Writes to disk can fail even when it returns success, even with a synchronous write, even after sync(). The world can lie to us. For your own sanity, I recommend not thinking about this often... > Neither of them fail often, but when they do, you can't just ignore it. You have to do something intelligent about it. Nope. You can often do very dumb shit in response to it. Just like you don't have to do anything intelligent when malloc() fails, you don't have to do anything intelligent when fork() fails. The most common thing to do is to restart whatever was failing , starting with the smallest "thing" and going up in size (threads->pids->pgroups->containers->vms->bare metal, tasks->services->clusters, etc). Of course, you should probably have some kind of cumulative alert to tell someone to fix it, but often the restart is good enough to keep requests being processed. Such is the reality of imperfect production systems.
- asveikau 7y ago> For your own sanity, I recommend not thinking about this often... If you mean this to say you shouldn't check for errors, I disagree. Write errors that fail with an error code are much more common than those that do not. The latter in my experience is usually a particularly bad hardware problem. For the most common write errors (including disk full, but also errors arising from hardware failures), I think you should make a best effort to check and flag it. The larger your base of installed machines, the more you will be thankful for this logging. You don't want to be diagnosing rare failures blindly. A low failure rate multiplied by a large install base leads to that problem daily. > Just like you don't have to do anything intelligent when malloc() fails This is also false in my experience. I have seen stuff in the field where malloc(40) [yes, that small] fails, and I am still able to log where that happens, write it to disk, and have it be recovered and read by me, the developer. I've also seen malloc fail and a UI program survive long enough to report the error to the user and maybe even retry the operation successfully. The reason for this has to do with how you react. In the first case: a log file write does not ordinarily result in memory allocation. [fprintf does, but there are other ways to log]. In the second case, firstly, mallocs that fail are often absurdly large, where a smaller malloc will succeed; and second, you will react to the malloc failure by unwinding your stack and this will have the side effect of many stack frames calling free(), which might give you enough space to keep going successfully.
- ColanR 7y agoSo do people just not read man pages? It's right there. On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. http://man7.org/linux/man-pages/man2/fork.2.html http://man7.org/linux/man-pages/man2/fork.2.html
- BanazirGalbasi 7y agoWhen I went through my university's C programming course, the instructor barely knew C. For the students with limited Linux experience, the concept of man pages was unknown to them, let alone that there are man pages for C functions. So no, people don't read man pages because they don't know they exist.
- ColanR 7y agoThat's a deficiency in the teaching, not the language. How much ignorance is excusable before it's the programmers fault for not knowing the language?
- BanazirGalbasi 7y agoDoes knowing C require knowing Linux\Unix? While I know there's a strong relationship between the two, I don't think that it's a hard requirement. You can learn C syntax and how to compile it with pretty minimal Linux\Unix exposure. I do agree that it was a deficiency in the way the course was taught, luckily that professor no longer teaches the course as it became obvious that he wasn't comfortable with Linux or C. Still, that's when it became apparent to me that if people will avoid using an environment they're uncomfortable with, they will. Some students made the grave sin of running their code in Visual Studio on Windows rather than using GCC, and it was accepted because the code worked. Those students graduated all the same, despite having no knowledge of man pages. It's a lot more common than you'd think (and more than I'd like).
- ColanR 7y ago
- deleted 7y ago[deleted]
- ambrop7 7y agoIn any case, if the program forks in order to exec, it shouldn't be using fork at all, but posix_spawn. Fork gets more expensive as the virtual memory of the process grows, since it needs to copy page tables. For very large process forking can be prohibitively expensive due to this. And posix_spawn does not have this problem.
- mzs 7y ago>… The true pain comes later when it's time to send a signal. Maybe you want to shut down a child process. >Do you kill(pid, signal)? Maybe you do kill(pid, 9). >Do you know what happens when pid is -1? …
- dang 7y agoDiscussed at the time: https://news.ycombinator.com/item?id=8204007 https://news.ycombinator.com/item?id=8204007
- nitwit005 7y agoWhat people usually mess up isn't checking the return code from fork, but checking the return code from the call from some exec variant after the fork. As you have two processes after the fork call, you have to pass exec error results back to the parent process through something like a pipe.