21 comments

  • rom1v5 hours ago
    Related to the discussion: &quot;A fork() in the road&quot;: <a href="https:&#x2F;&#x2F;www.microsoft.com&#x2F;en-us&#x2F;research&#x2F;wp-content&#x2F;uploads&#x2F;2019&#x2F;04&#x2F;fork-hotos19.pdf" rel="nofollow">https:&#x2F;&#x2F;www.microsoft.com&#x2F;en-us&#x2F;research&#x2F;wp-content&#x2F;uploads&#x2F;...</a><p>&gt; ABSTRACT<p>&gt; The received wisdom suggests that Unix’s unusual combination of fork() and exec() for process creation was an inspired design. In this paper, we argue that fork was a clever hack for machines and programs of the 1970s that has long outlived its usefulness and is now a liability. We catalog the ways in which fork is a terrible abstraction for the modern programmer to use, describe how it compromises OS implementations, and propose alternatives.<p>&gt; As the designers and implementers of operating systems, we should acknowledge that fork’s continued existence as a first-class OS primitive holds back systems research, and deprecate it. As educators, we should teach fork as a historical artifact, and not the first process creation mechanism students encounter.
    • Animats3 hours ago
      &gt; The received wisdom suggests that Unix’s unusual combination of fork() and exec() for process creation was an inspired design.<p>No, it was done that way so that you could launch a program that was too big to fit in memory with the parent program. The original implementation worked by swapping out the forking program to disk on a fork() call. Then, at the moment the program was swapped out but control had not returned, the process table entry was duplicated and adjusted so that there were now two processes, one in memory and one swapped out. The one in memory then got control, and could do an exec() call.<p>This allowed large programs to run on small PDP-11 machines. It was needed back in the era of really expensive memory. That&#x27;s why.<p>QNX had an interesting approach. Program loading isn&#x27;t in the OS at all. There&#x27;s &quot;fork&quot;, but program loading is in a library. It links to a .so file which reads the executable header, allocates memory, loads the program, gets it ready to run, and starts it. The program loader runs in user space and is unprivileged. This is probably the right way to do it.
      • bluepuma771 hour ago
        &gt; It was needed back in the era of really expensive memory.<p>Well, it seems we are back in an era with really expensive memory.
      • not_a_bijection2 hours ago
        I think fork() is more of a PDP-7 mistake than a PDP-11 mistake. On the original UNIX system, memory was so limited that the only sane partitioning was to write the running program&#x27;s memory image to disk, then reuse the running image as the child. An immediate consequence is the UNIX I&#x2F;O model, where disk I&#x2F;O is always synchronous (can&#x27;t swap processes while waiting for disk I&#x2F;O because swapping processes requires disk I&#x2F;O). Anyway, as soon as the UNIX group got a PDP-11, the model broke down, because they had enough memory for multiple processes, but fork() didn&#x27;t allow them to run concurrently, because their first PDP-11 didn&#x27;t have an MMU. So they whined until they got one with an MMU instead of fixing their broken design.
      • dcrazy3 hours ago
        Don’t pretty much all OSes implement process startup in userspace? On macOS, the kernel creates a process with an image of dyld and points it at dyld_start, which actually takes care of parsing the Mach-O header. I assumed ld.so does the same job on Linux.
        • purkka52 minutes ago
          Nope, the kernel can load static ELF binaries. ld.so is only needed for dynamically linked binaries, and in fact many Go applications (for example, as they&#x27;re statically linked) ship as containers with nothing but the single binary.
          • dcrazy24 minutes ago
            Thanks. I completely forgot about static binaries.
            • loeg9 minutes ago
              Of course ld-linux itself is an ELF binary. The kernel loads it.
      • lukan3 hours ago
        It is almost as if you agree with the authors ..<p>&quot;In this paper, we argue that fork was a clever hack for machines and programs of the 1970s that has long outlived its usefulness and is now a liability&quot;<p>(But thanks for the good explanation)
      • duped2 hours ago
        &gt; It links to a .so file which reads the executable header, allocates memory, loads the program, gets it ready to run, and starts it. The program loader runs in user space and is unprivileged. This is probably the right way to do it.<p>aiui this is what exec does, the problem outlined here is the split between process creation (expensive, kernel space, has to be done each time even if spawning the same process &quot;template&quot; repeatedly) and loading (cheap and in userspace).
    • anarazel5 hours ago
      It is somewhat interesting that the most widely used &quot;big&quot; OS that doesn&#x27;t use fork, i.e. Windows, has dog slow process creation...<p>I agree that there should be non-fork primitives, I&#x27;m just not that sure that performance is the best argument.
      • mort964 hours ago
        The problem with fork isn&#x27;t really that it&#x27;s slow. The problem is that if you want it to be not-slow, it locks you into a bunch of OS design decisions: you more or less need a memory subsystem where all writable pages are refcounted and copy-on-write when the refcount is bigger than 1, and you need overcommit.<p>Now these decisions aren&#x27;t <i>objectively bad</i>, but they have significant trade-offs and it&#x27;s <i>probably</i> not a good idea that they&#x27;re forced simply because we use fork()+exec() for process creation.
        • tliltocatl20 minutes ago
          In addition to what you said: forking from a process running on multiple cores is slow once you have mark all pages as read-only and shoot this out to all cores. TLB synchronization is super expensive. Unix originally didn&#x27;t support threads (want concurrency? just fork!) but with modern multicore that&#x27;s clearly unsustainable.
        • marcosdumay4 hours ago
          CoW is probably a good idea whether you use fork or not. Or rather, fork is probably a better option than just exec exactly because it can benefit from CoW.<p>At least on systems with virtual addressing. If you want to go into physical addressing, then yes, maybe it&#x27;s a problem. But Linux will never touch anything with physical addressing, so I don&#x27;t see what people are complaining about.
          • mort962 hours ago
            CoW is probably a good idea regardless, yeah. Overcommit is more questionable. Regardless, both ought to be argued based on their own merits. It&#x27;s unfortunate that both are necessary as a consequence of fork().
            • mpyne1 hour ago
              I don&#x27;t think fork() mandates overcommit. OpenBSD doesn&#x27;t seem to even allow overcommit or have an OOM killer, memory allocations that exceed available capacity fail immediately even if the memory is not touched.
              • vbezhenar1 hour ago
                Let&#x27;s say you have 1GB RAM. You&#x27;re running program that occupies 600 MB. Now this program wants to launch second small program that occupies 1 MB.<p>You&#x27;re doing fork + exec.<p>If you&#x27;re overcommiting, fork will not reserve another 600 MB, and exec immediately after fork will cause total system usage to be 601 MB.<p>If you&#x27;re not overcommiting, that fork will fail, because total memory consumption will be 1200 MB which is more than 1GB. That somewhat restricts program design.
        • Someone3 hours ago
          &gt; The problem with fork isn&#x27;t really that it&#x27;s slow. The problem is that if you want it to be not-slow, it locks you into a bunch of OS design decisions: you more or less need a memory subsystem where all writable pages are refcounted and copy-on-write when the refcount is bigger than 1<p>It may not be slow, but for the common case where <i>fork</i> is almost immediately followed by <i>exec</i> in the process where <i>fork</i> returns zero <i>fork</i> increases those refcounts and <i>exec</i> almost immediately decreases them again hand does typically unnecessary checks whether refcounts became zero). A combined <i>fork</i>&#x2F;<i>exec</i> syscall can avoid that work.<p>On the other hand, a sufficiently powerful combined <i>fork</i>&#x2F;<i>exec</i> call has to have a lot of parameters that it has to check (whether to inherit open pipes, open files, setting the working directory, etc), and that slows it down.<p>That can be avoided by having multiple variants of combined <i>fork</i>&#x2F;<i>exec</i> calls, but you would need lots of them to cover all combinations of flags.<p>I expect either approach should be faster then having <i>fork</i>, then <i>exec</i> as separate calls, especially when the process calling <i>fork</i> has many resources allocated.
          • thayne40 minutes ago
            Another possible design is instead of forking the current process, you create a new empty process, then the parent calls syscalls to set up the new process, and eventually call exec on the child process. That does mean you either need new syscalls for that, or adapt existing syscalls to take a pidfd as an argument. That also solves some other problems with fork&#x2F;exec where the default is to inherit a lot of things you probably don&#x27;t want. With this, you can opt in to inheritance instead of having to opt out.<p>Or you could create a hybrid between a thread and a process, where it still uses the parent&#x27;s memory space (unlike fok), but has it&#x27;s own stack (unlike vfork), and is in its own process (unlike a thread). I think this is technically possible on linux, but there isn&#x27;t a readily available interface for it. Although it seems like posix_spawn could be implemented that way...
            • dcrazy21 minutes ago
              Syscalls aren’t all that cheap either.
        • thayne57 minutes ago
          With large enough processes, like say a server JVM process that uses 10s of GBs of RAM, even just copying the page tables for CoW can be slow. And unless you have aggressive overcommit settings you can get an OOM on fork, even if you&#x27;re just going to exec something small.<p>vfork helps a little, but it has a lot of restrictions on what you can do before the exec, and on unix that&#x27;s basically the only place you can do things like close files, change signal masks, drop privileges or set up seccomp, etc.
        • adgjlsfhk11 hour ago
          One os level thing that is interesting to me is if it would be possible&#x2F;wise to make an OS based on (concurrent) garbage collection.
        • theK4 hours ago
          Didn&#x27;t he just say that fork turns out to be comparatively faster to the non-fork samples we get? Ie Linux spawns processes faster than Microsoft&#x27;s kernels?
          • mort964 hours ago
            Didn&#x27;t I just say that &quot;the problem with fork isn&#x27;t really that it&#x27;s slow&quot;? It&#x27;s all the other OS design choices it forces on you if you want it to be fast.
            • theK3 hours ago
              Right, you did. I somehow misread your comment.
          • nvme0n1p14 hours ago
            We don&#x27;t have any broadly used non-fork samples. Windows, macOS, and Linux all have fork. So the presence of fork can&#x27;t be the reason for the performance difference.<p>(Windows&#x27;s fork is called ZwCreateProcess)
            • dcrazy4 hours ago
              NtCreateProcess does not implement a forking model. It is analogous to posix_spawn.
              • nvme0n1p11 hour ago
                If you pass null for the section handle, it shares pages with the calling process, thus implementing a forking model. Or at least the parts of a forking model that some people erroneously believe are responsible for performance differences.
            • Someone3 hours ago
              MacOS has <i>posix_spawn</i>. See <a href="https:&#x2F;&#x2F;developer.apple.com&#x2F;library&#x2F;archive&#x2F;documentation&#x2F;System&#x2F;Conceptual&#x2F;ManPages_iPhoneOS&#x2F;man2&#x2F;posix_spawn.2.html" rel="nofollow">https:&#x2F;&#x2F;developer.apple.com&#x2F;library&#x2F;archive&#x2F;documentation&#x2F;Sy...</a> (yes, that’s an iOS man page. MacOS has the call, too, but I couldn’t find the man page online and it looks identical to me)<p>I don’t know how they implemented it, though. Under the hood, it <i>could</i> do the equivalent of a <i>fork</i>&#x2F;<i>exec</i> pair.
              • dcrazy16 minutes ago
                XNU is open source; here’s a link into the middle of the implementation, after it’s copied all the necessary attributes of the parent into the new process structure: <a href="https:&#x2F;&#x2F;github.com&#x2F;apple-oss-distributions&#x2F;xnu&#x2F;blob&#x2F;f6217f891ac0bb64f3d375211650a4c1ff8ca1ea&#x2F;bsd&#x2F;kern&#x2F;kern_exec.c#L4039" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;apple-oss-distributions&#x2F;xnu&#x2F;blob&#x2F;f6217f89...</a>
              • plorkyeran2 hours ago
                XNU&#x27;s posix_spawn implementation is not fork&#x2F;exec-based. It does roughly what the API suggests it would do.
        • dapperdrake3 hours ago
          How else does consistency work, then?<p>Only being half facetious here. Maybe you or someone else really has a better take.
          • mort963 hours ago
            What do you mean by consistency here?
        • foresto3 hours ago
          &gt; The problem with fork isn&#x27;t really that it&#x27;s slow.<p>Did someone suggest that it was?
          • mort962 hours ago
            anarazel&#x27;s comment focuses entirely on performance, indicating that they have an impression that the discussion about why fork is bad is about performance. I&#x27;m not entirely sure where this impression came from, as it&#x27;s not mentioned in rom1v&#x27;s quote nor a point in the linked paper, &quot;A fork() in the road&quot;.
      • pjmlp5 hours ago
        Because that OS best practices is to use threads.<p>Traditionally Windows applications that create processes all the time come from UNIX heritage.<p>Contrary to UNIX, Windows NT was designed with threads first mentality, from the get go.<p>While on UNIX they were added after fact, and to this day there are gotchas mixing posix threads with signals, fork and exec.
        • PaulDavisThe1st3 hours ago
          A more accurate way to describe this is that Windows&#x27; (NT onward) core execution context model is a bunch of threads that by default share memory, whereas Unixen have a core task context model of a bunch of threads that by default do not share memory.<p>Both systems are implemented using threads as the execution context, but in Unix, the history means that that you fork+exec most of the time, resulting in a two tasks that do not share memory any more. By contrast, on Windows (NT onward) the common case when creating a new execution context is to create a thread that shares memory with others in its process.<p>Both systems <i>allow</i> the easy use of the other&#x27;s core abstraction. On Unix, you can either code like its 1986 and use fork without exec, or use clone(3) or any of its higher level abstractions like pthreads.<p>You&#x27;re right that POSIX semantics get tangled when using threads.
          • JdeBP2 hours ago
            That&#x27;s actually less accurate, not more. It&#x27;s a post-hoc revision that conflates Unix with Linux.<p>The Unix model was invented over a decade before the idea of multithreading percolated into mainstream operating systems at all.<p>The reason that Windows NT started as it did, was that OS&#x2F;2 had come out in 1987, with kernel threads, and the idea of multithreading had taken root. SunOS 5 gained threading, too.<p>Windows NT applications development began with threading available as a mechanism from the start, and with a lot of people in the IBM&#x2F;Microsoft world already knowing about its use in applications development from OS&#x2F;2.<p>Whereas with the Unices it came in more gradually, as the applications had often already been designed. The whole libthread versus libpthread thing made things interesting on SunOS for a few years, too. As did the first attempt (LinuxThreads) at providing threads on Linux.
          • pjmlp3 hours ago
            Well, Windows before NT isn&#x27;t the same design as Windows 16 bit, it only shares the name for all practical purposes, and has more influence from OS&#x2F;2 than Windows 16 bit.<p>Which is why I took the effort to explicitly refer to Windows NT on my comment, already expecting some traditional answers from UNIX folks.<p>Also due to historical reasons POSIX threads are the outcome of every UNIX going their own way implementing threads, finally coming to an agreement years later, with all the plus and minus of relying in POSIX for portable code.
          • snozolli3 hours ago
            <i>whereas Unixen have a core task context model of a bunch of threads that by default do not share memory.</i><p>How are those not simply child processes? I don&#x27;t understand your use of the word &#x27;threads&#x27; here.<p>Does the Unix world not distinguish between threads and processes? In Win32, threads exist within processes, and you can create new threads or child processes.
            • trumpdong3 hours ago
              They are child processes.<p>Second answer: Linux doesn&#x27;t differentiate between threads and processes. It has a &quot;thread group ID&quot; that serves a small number of purposes, and the rest of the difference is just whether the threads happen to share the same address space.
            • pjmlp3 hours ago
              Actually on Windows a process is a thread with additional information.<p>The unit of execution is the thread.<p>On the UNIX world it depends on which UNIX you are talking about.<p>Linux has a similar model to Windows NT nowadays, hence clone() as key primitive.<p>Other UNIXes have different approaches.
        • sunshowers3 hours ago
          The problem is that threads are not fault boundaries but processes are. So they&#x27;re not interchangeable when you care about resilience and misbehaving code.
          • pjmlp3 hours ago
            True, but on Windows the approach is then to use COM servers, which have a faster IPC model, and can even serve multiple clients, depending on how the appartement space is configured.
            • dcrazy10 minutes ago
              If you want the isolation features of a separate process, you can’t substitute it with a single multithreaded COM server process.<p>.NET tried this with app domains, which are now deprecated.
            • mort962 hours ago
              &quot;Faster IPC model&quot; than what? Faster than writing to and reading from a pipe? Faster than POSIX shared memory?
              • pjmlp1 hour ago
                Than UNIX fork&#x2F;exec model, or calling into Create Process all the time.<p>Windows has a more rich set of IPC stuff than POSIX, especially since it has a microkernel like design.<p>If you are going to say it is everything on the same memory space anyway, it isn&#x27;t.<p>Optional on Windows 10, and enforced on Windows 11, Hyper-V is always running, and several components including kernel and driver modules are sandboxed into their little worlds.<p>Several additional sandboxing changes were announced at BUILD.
                • mort961 hour ago
                  fork&#x2F;exec is not an IPC model...
        • zozbot2345 hours ago
          Windows was designed with threads-first mentality because on pre-386 machines you don&#x27;t have viable process memory protection, so your tasks share memory by necessity. This is not a great argument.
          • JdeBP4 hours ago
            Windows NT was never designed with pre-386 machines in mind. That was the territory of the old DOS+Windows. Windows NT from the get-go was for machines with page-based virtual memory.<p>* <a href="https:&#x2F;&#x2F;computernewb.com&#x2F;~lily&#x2F;files&#x2F;Documents&#x2F;NTDesignWorkbook&#x2F;vm.pdf" rel="nofollow">https:&#x2F;&#x2F;computernewb.com&#x2F;~lily&#x2F;files&#x2F;Documents&#x2F;NTDesignWorkb...</a>
            • pstuart3 hours ago
              WinNT 3.5 was a solid offering.
          • epcoa4 hours ago
            This is not true. NT never had fork, was always based on the assumption of an MMU and Dave Cutler was a well known fork hater in the 80s long before this paper came out and made it cool to be so. By the time Windows 95 was out, the baseline was 386 with an MMU. CreateThread was initially designed for NT in 1993 though (which didn’t support pre-386 CPUs).
            • keitmo3 hours ago
              NT performed unnatural acts to implement fork semantics for the POSIX subsystem.
            • JdeBP4 hours ago
              As mentioned elsewhere on this page, Windows NT had fork from the start. Vide NtCreateProcess and what happens if an image file is not explicitly supplied.<p>* <a href="https:&#x2F;&#x2F;computernewb.com&#x2F;~lily&#x2F;files&#x2F;Documents&#x2F;NTDesignWorkbook&#x2F;proc.pdf" rel="nofollow">https:&#x2F;&#x2F;computernewb.com&#x2F;~lily&#x2F;files&#x2F;Documents&#x2F;NTDesignWorkb...</a>
              • dcrazy3 hours ago
                NtCreateProcess doesn’t accept an image file parameter.
                • JdeBP2 hours ago
                  You haven&#x27;t read the doco. I did point to some. The image file is supplied (or not) via the section object.<p>Think it through. Windows NT supported fork from the start in its POSIX subsystem, that subsystem was layered on top of the Native API, and this is the Native API mechanism that the POSIX subsystem employed. Although it took until Gary Nebbett for someone to publicly show how, even though people knew informally back in 1993.
          • dcrazy3 hours ago
            NT was designed to be platform-agnostic, and its original target was the DEC Alpha. Its process model owes nothing to pre-386 CPUs. The WinAPI CreateProcess function is a layer atop NtCreateProcess, so that is where the pre-386 heritage lives. But even the WinAPI process model changed significantly with 32-bit Windows.
          • pjmlp4 hours ago
            Windows NT!<p>Misread on purpose to make a point?
        • knome3 hours ago
          the only difference between a thread and a process on linux is how many structures they share. the function is identical.
          • pjmlp1 hour ago
            Agreed, however not all UNIXes are like Linux.
      • aseipp5 hours ago
        I suspect it&#x27;s a long tail sort of thing; it mostly doesn&#x27;t matter except when it really matters. It&#x27;s interesting that the stated motivation for the patch is in the context of agentic tools spawning subcommands. There&#x27;s some related prior art in this area where the payoffs could be much greater, like fuzzing: <a href="https:&#x2F;&#x2F;gts3.org&#x2F;assets&#x2F;papers&#x2F;2017&#x2F;xu:os-fuzz.pdf" rel="nofollow">https:&#x2F;&#x2F;gts3.org&#x2F;assets&#x2F;papers&#x2F;2017&#x2F;xu:os-fuzz.pdf</a> is an example. It would be very interesting to see this patch applied to e.g. AFL++
      • nvme0n1p15 hours ago
        That&#x27;s not the reason for the performance difference. Windows does have a fork primitive (ZwCreateProcess) and it&#x27;s still slower than Linux&#x27;s equivalent.
        • dcrazy3 hours ago
          Again, NtCreateProcess does not implement fork(). The fundamental characteristic of fork is that the child is an exact replica of the parent, down to the instruction pointer. Windows does not have a way to create a process object with such a configuration.<p>Also, using the Zw prefix doesn’t make you look more knowledgeable, it makes you look like you’re trying way too hard to borrow credibility.
          • nvme0n1p11 hour ago
            Okay but people don&#x27;t claim that copying the instruction pointer (a single machine register) is the reason for any speed difference. They claim it&#x27;s due to the memory sharing. And that&#x27;s easily disproven since you can share pages, just like on Linux, simply by passing null for the section handle, yet there&#x27;s still a performance difference.<p>Why does it matter which prefix I used? They both point to the same routine so my point applies either way.
    • aseipp5 hours ago
      This paper is great and I also really like one of its references [29] as it goes into some more subtle parts of scalable interfaces, including fork. It&#x27;s a gem IMO: The Scalable Commutativity Rule: Designing Scalable Software for Multicore Processors <a href="https:&#x2F;&#x2F;people.csail.mit.edu&#x2F;nickolai&#x2F;papers&#x2F;clements-sc.pdf" rel="nofollow">https:&#x2F;&#x2F;people.csail.mit.edu&#x2F;nickolai&#x2F;papers&#x2F;clements-sc.pdf</a>
    • omoikane5 hours ago
      Discussion at the time:<p><a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=19621799">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=19621799</a> - A fork() in the road (2019-04-10, 178 comments)
      • jwilk3 hours ago
        Discussed also in 2021: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=29709802">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=29709802</a> (16 comments)
    • pizlonator5 hours ago
      Fork is marvelous for the zygote pattern<p>Hard to come up with an optimization that is equally efficient and elegant
      • toast05 hours ago
        The zygote pattern[1] is a great optimization to deal with the cost of forking, but IMHO, being able to inexpensively spawn a carefully tailored process regardless of the size and scope of the current process would be better.<p>I would guess it would be a small difference in measurable performance between zygote and a direct clean spawn, but it&#x27;s one less trick an application needs to do, and it would be very helpful for libraries that spawn things. Spawning inside a library isn&#x27;t always a great thing to do, but some things would really benefit from process level isolation.<p>[1] In case one isn&#x27;t aware, the zygote pattern involves forking a &#x27;zygote&#x27; process during application startup, and having that process do any forks that need to happen during application runtime. This reduces the cost of forking in large applications, because the zygote will have few fds open and use little memory. This lets your large application spawn new processes without delaying the application or the startup of the new processes. Some applications will spawn many zygotes to allow parallelism for spawning at runtime.
        • pizlonator4 hours ago
          You&#x27;re referring to something else, and maybe I&#x27;m using the term &quot;zygote&quot; incorrectly.<p>In all uses of zygotes that I have seen, here&#x27;s what&#x27;s really happening:<p>- `fork` is being used to reduce the cost of starting a process that has a high start-up cost. So, you start one process, run it through the expensive initialization, and then fork it from there to start new processes.<p>- To make this even faster, you have a pool of pre-forked processes sit around.<p>- Having pre-forked processes sitting around ready to be used is not expensive because of the CoW property and the fact that a process that forks and then immediately pauses will not have triggered any significant CoW yet.<p>So, the zygote optimization you speak of is in practice only meaningful on top of systems that are using an optimization uniquely enabled by `fork` (avoiding process initialization costs by cloning a process), and that zygote optimization is further optimized by another property of `fork` (memory sharing of forked processes that haven&#x27;t done anything else yet).
          • toast04 hours ago
            Oh I see. I guess your zygotes have developed more than mine. I <i>think</i> Google may have coined or at least popularized the term zygote for this in Chrome and Android, Chrome documentation [1] says:<p>&gt; A zygote process is one that listens for spawn requests from a main process and forks itself in response. Generally they are used because forking a process after some expensive setup has been performed can save time and share extra memory pages.<p>I think reading the first sentance and stopping covers my zygote, but adding the second sentance covers yours. So I think we&#x27;re both right!<p>I think both paths are useful. If your children need time to startup and become ready, spawn one that does start up work, and then it (pre)forks at the ready state to have processes ready to handle requests (your zygote). This <i>does</i> require a traditional fork() to avoid duplication of work.<p>But if forking is expensive at runtime because you have a million FDs open and a whole lot of memory allocations, spawn spawners before you start doing work (my zygote). This could be unnecessary with a inexpensive way to spawn a new process from an process that has lots of resources in use.<p>Of course, you can also use my zygotes to spawn your zygotes. Zygoteception.<p>[1] <a href="https:&#x2F;&#x2F;chromium.googlesource.com&#x2F;chromium&#x2F;src&#x2F;+&#x2F;HEAD&#x2F;docs&#x2F;linux&#x2F;zygote.md" rel="nofollow">https:&#x2F;&#x2F;chromium.googlesource.com&#x2F;chromium&#x2F;src&#x2F;+&#x2F;HEAD&#x2F;docs&#x2F;l...</a>
            • mpyne1 hour ago
              &gt; Oh I see. I guess your zygotes have developed more than mine. I think Google may have coined or at least popularized the term zygote for this in Chrome and Android, Chrome documentation [1] says:<p>Google may have popularized the term, but this approach was already in use by KDE developers in the KDE 2.x timeframe, where it was used as part of a system called kdeinit.<p>In this scheme, launching KDE apps from a KDE desktop could bypass much of the startup cost of dynamic linking by forking from a long-running kdeinit process (with kdeinit itself deliberately linked to all large dependency libs like Qt and kdelibs), dynamically loading the application logic (stored as a .so) and then launching the app.<p>This was more to save startup time due to how long it took to dynamically resolve a multitude of C++-based symbols back then, all the common logic came before the app&#x27;s own main() would ever be called. But it did also save a bit of memory as well.
            • skydhash3 hours ago
              I quite like the idea. I’m using OpenBSD on an oldish laptop, and fork-exec is expensive enough that it conflicts with the usb subsystem. Isochronous transfers have a 1ms realtime requirement and it seem that the fork-exec system calls hold the giant lock long enough to mess with it (audio stutters).<p>While I’ve not bothered to profile it, but it seems that process that have lot of mapped pages is the issue (firefox, emacs,…). In the emacs case, the issue is when the main process trying to fork-exec, if I start a shell session (with shell-mode or term-mode), it works fine.
        • PaulDavisThe1st3 hours ago
          &gt; being able to inexpensively spawn a carefully tailored process regardless of the size and scope of the current process would be better.<p>It&#x27;s called clone(2)
          • toast054 minutes ago
            adding on the the sibling, what argument to clone allows me to set the fds of the child? AFAIK, you either share the FD table with the parent, or get a copy of it. If the parent has 1 million FDs open and the child doesn&#x27;t want most of those, dealing with that has real costs. Many applications that tend to have large numbers of FDs and also fork&#x2F;exec will mitigate the cost by spawning a process during startup that they can then use to spawn processes during runtime without doing it from the main process; this is a nice mitigation, but it shows a missing interface.
          • trumpdong3 hours ago
            Which argument to clone starts the process with an empty address space?
      • vlovich1234 hours ago
        The paper explicitly covers it that various memory COW&#x2F;snapshot mechanisms are probably faster and safer than the zygote pattern. As it stands getting the zygote pattern correct and safe is something you have to plan for upfront. You can’t retrofit it which is why the paper mentions it has poor composability. Also the advantages of the zygote pattern can be overstated since the memory sharing benefit is minimal since it has to happen so early and modern OSes already transparently CoW duplicate pages in the background.
        • loeg3 hours ago
          In what sense can you not retrofit the zygote pattern?
      • p_l2 hours ago
        And so easy to make into bottleneck.<p>Yes, zygote pattern makes it easy to make fork() into bottleneck - it requires a lot more discipline and low level tricks (linker scripts, compiler-specific extensions, custom sections, low level dependencies on pagesize that get &quot;fun&quot; on ARM servers).<p>If you don&#x27;t, you might wake up with fork() causing latency issues.
  • sanderjd6 hours ago
    I just ran into this recently, where I had an obscure bug caused by needing to close more file descriptors in the forked process. &quot;I want a clone of the current process&quot; is just way less common in my experience than &quot;I want a completely new process&quot;. It feels crazy that we don&#x27;t have a way to directly express the latter thing, and can only approximate it by cloning and then fixing things up in post.
    • 17186274405 hours ago
      But you generally want to communicate with that process, so you do need to setup e.g. file descriptors and stuff, which needs information from the parent process to be passed.
      • yxhuvud4 hours ago
        Yes, you do want to pass in some stuff. But by default you get every single open file descriptor and a copy of every single stack that any threads use for execution.<p>It shares way too much, and have huge use cases where it is really, really bad.
      • sanderjd1 hour ago
        Nevertheless, inclusion would be a better default than exclusion in most use cases I&#x27;ve ever had for process spawning.
      • jonhohle5 hours ago
        Most programming languages abstract this out to be able to connect or drop the 3 standard pipes. Typically this is the only thing that can be shared anyway unless the other program is specifically shared and expects other file handles to be available, in which case fork might be the right system call anyway.
        • sanderjd1 hour ago
          Right. It&#x27;s not that fork is useless, it&#x27;s that it&#x27;s weird that it&#x27;s the only way to do this thing that it isn&#x27;t particularly well suited for.
      • stefan_4 hours ago
        Keep in mind that <i>this is the only way to start any process</i>. Even if you just want to launch some throwaway utility program.
    • dnw6 hours ago
      What do you mean by &quot;a completely new process&quot;?
      • wongarsu5 hours ago
        The equivalent of CreateProcessW <a href="https:&#x2F;&#x2F;learn.microsoft.com&#x2F;en-us&#x2F;windows&#x2F;win32&#x2F;api&#x2F;processthreadsapi&#x2F;nf-processthreadsapi-createprocessw" rel="nofollow">https:&#x2F;&#x2F;learn.microsoft.com&#x2F;en-us&#x2F;windows&#x2F;win32&#x2F;api&#x2F;processt...</a>
      • sanderjd6 hours ago
        A process that shares nothing with the process that spawned it.
        • jerf5 hours ago
          A thing that makes that complicated is that while you want that conceptually, you don&#x27;t want that in reality. For instance, if the spawning process is in a container of some sort and it spawned a process that &quot;shares nothing with the process that spawned it&quot;, the spawned process would no longer be in that container, because the state of &quot;being in the container&quot; is one of the things it shares with the parent process.<p>This is just an example of I don&#x27;t even know how many things a modern-day process will share from its parent.<p>By &quot;complicated&quot; I do not even remotely mean &quot;unsolvable&quot;. I just mean that if you really dig down into what it means to &quot;share nothing&quot; in a modern operating system, it&#x27;s a lot richer than it was back when fork+exec was a practical solution. There&#x27;s a lot of fuzzy things that could go either way when you say &quot;shares nothing&quot;.
          • sanderjd1 hour ago
            Yes, stipulated. And it it&#x27;s true that we should have a primitive for spawning a completely new process, because that&#x27;s what we usually want. I agree that the details are both non trivial and soluble.
          • dcrazy2 hours ago
            It’s such a bad idea that every OS except Linux implements it? On macOS it’s posix_spawn, on Windows it’s NtCreateProcess.
            • jerf2 hours ago
              Who said anything about it being a &quot;bad idea&quot;?<p>I also explicitly said this wasn&#x27;t unsolvable. My point isn&#x27;t about technical implementations or code, my point is that the casual &quot;I want to share nothing about the parent process&quot; thought in sanderj&#x27;s mind, and presumably a lot others, is much more ill-defined than they realize. There&#x27;s a lot more state that a process has than what file descriptors are open in a modern system.<p>Moreover, as things like &quot;in which container is this running&quot; demonstrate, those are <i>also</i> not &quot;create a process that has nothing to do with this process&quot;, because, again, there&#x27;s a lot more to &quot;having to do with this process&quot; than &quot;what file descriptors are open&quot;.<p>Also, as the name might have been a clue, Linux has posix_spawn: <a href="https:&#x2F;&#x2F;linux.die.net&#x2F;man&#x2F;3&#x2F;posix_spawn" rel="nofollow">https:&#x2F;&#x2F;linux.die.net&#x2F;man&#x2F;3&#x2F;posix_spawn</a>. It also has a thing called &quot;clone&quot;: <a href="https:&#x2F;&#x2F;www.man7.org&#x2F;linux&#x2F;man-pages&#x2F;man2&#x2F;clone.2.html" rel="nofollow">https:&#x2F;&#x2F;www.man7.org&#x2F;linux&#x2F;man-pages&#x2F;man2&#x2F;clone.2.html</a> Nor do I claim this paragraph is an entire overview of all the ways of starting a process in Linux. If you want to understand what I mean by &quot;lots of details in a modern OS&quot;, your assignment is to carefully read the entire &quot;clone&quot; man page, and you&#x27;ll start to see what I mean, though I&#x27;m not sure even that is all the state associated with a process nowadays.
              • sanderjd1 hour ago
                It&#x27;s not a casual thought. I recognize that there are lots of details, there always are, we&#x27;re talking about computers :)<p>I don&#x27;t think it is necessary (or the best implementation) to clone the parent process, in order to maintain important properties like the process tree &#x2F; container state, etc. I recognize that it&#x27;s a sorta neat hack, &quot;well if we just start by cloning the parent, then we don&#x27;t have to figure out what state to include!&quot;, but that just pushes the details to the child process needing to figure out what to exclude, which IMO is a worse default.
              • dcrazy2 hours ago
                Linux posix_spawn is a wrapper around clone and exec. There is no primitive on Linux to create an entirely blank process. This is adequately discussed in the linked LWN post.<p>Other operating systems either have parallel APIs to fork (e.g. the posix_spawn syscall on macOS) or do not provide fork at all (Windows).
        • JoBrad5 hours ago
          That’s how you get zombie processes and memory leaks.
    • stabbles5 hours ago
      Isn&#x27;t that covered by O_CLOEXEC?
      • sanderjd33 minutes ago
        I think it is error prone to need to iterate file descriptors and set this in order to inherit nothing. Excluding by default would make sense IMO.
      • anarazel5 hours ago
        There&#x27;s a bunch of nastiness around that too. If you have e.g. library state that assumes the fd still works you can get her very confusing bugs once another file is opened into that fd number...
        • JdeBP4 hours ago
          You may be mixing up fork and exec. Library data state isn&#x27;t retained over execve(), and O_CLOEXEC does not take effect at fork().
          • anarazel3 hours ago
            Indeed. Not enough coffee, apparently.
    • 7jjjjjjj4 hours ago
      &gt;It feels crazy that we don&#x27;t have a way to directly express the latter thing<p>Isn&#x27;t that what posix_spawn is for?
      • toast04 hours ago
        posix_spawn addresses the need from userspace. Under the hood, it&#x27;s still doing more or less a fork&#x2F;exec, with the baggage that comes with it. A syscall would be nicer.
      • yxhuvud4 hours ago
        And how do you think posix_spawn is implemented?
        • JdeBP3 hours ago
          This is an oft-overlooked point. An obvious place to look for improving fork+execve is to see whether posix_spawn can be given more efficient kernel mechanisms to be based upon.<p>And of course that has already been done. On NetBSD, posix_spawn() is a fully-fledged system call and much of the work is done in kernel mode.<p>* <a href="https:&#x2F;&#x2F;blog.netbsd.org&#x2F;tnf&#x2F;entry&#x2F;posix_spawn_syscall_added" rel="nofollow">https:&#x2F;&#x2F;blog.netbsd.org&#x2F;tnf&#x2F;entry&#x2F;posix_spawn_syscall_added</a>
          • dcrazy2 hours ago
            This is literally discussed in the article this post links to.
            • JdeBP2 hours ago
              Not really. They didn&#x27;t get anywhere near as far as noticing the prior art of NetBSD, not even on the mailing list discussion behind that article.
  • mrkeen5 hours ago
    &gt; fork() is a relatively expensive system call; it must copy the entire process state (including memory) for the child process. Many optimizations have been made over the years, but a fork is still a fundamentally costly operation. To make things worse, a fork() call is often immediately followed by an exec(), which will discard all of that memory that was so carefully copied for the child.<p>It&#x27;s weird to leave out a mention of copy-on-write - the optimisation that means that you <i>don&#x27;t</i> copy over all the memory.
    • tux35 hours ago
      This was left implicit in the article, but what they mean by copying the process state here is the memory management structures. That&#x27;s mainly the page tables and the VMAs.<p>That means you have to allocate new pages to hold a copy of all these structures, even if the actual memory pointed by the pages is shared. And walking all those structures to make a copy is still costly.
    • thamer1 hour ago
      Redis is the kind of process where this matters a lot, and while fork() doesn&#x27;t copy the memory, it still needs to copy the page table. For a process holding tens of GBs of RAM, fork() can take a <i>long</i> time, and there&#x27;s one every time Redis dumps its .rdb file or rewrites its binary log (&quot;AOF&quot;).<p>Even back in 2012 this blog post showed the high cost of this operation: <a href="https:&#x2F;&#x2F;redis.io&#x2F;blog&#x2F;testing-fork-time-on-awsxen-infrastructure&#x2F;" rel="nofollow">https:&#x2F;&#x2F;redis.io&#x2F;blog&#x2F;testing-fork-time-on-awsxen-infrastruc...</a><p>On an m2.xlarge using ~25GB of RAM, fork() took 5.67 seconds. That&#x27;s a long pause when Redis clients typically experience single-digit msec latency for most operations. Yes, that&#x27;s only the time needed to copy the page table. It&#x27;s surprising they don&#x27;t mention huge pages, it seems like it would be a key consideration here.<p>No doubt hardware is faster 14 years later, but Redis instances likely use more RAM too. It&#x27;d be interesting to see this benchmark revisited.
    • epcoa5 hours ago
      &gt; It&#x27;s weird to leave out a mention of copy-on-write<p>For the intended audience of such a paper this is base knowledge.
    • cls595 hours ago
      Even with copy-on-write, fork() still has to pay the setup cost for COW. If the parent process has a lot of busy threads (e.g. Java), you can end up doing a lot of unnecessary COW before exec() fires.
      • josefx2 hours ago
        Isn&#x27;t that what vfork tried to address? No COW, the child starts in its parents address space and only gets its own after calling exec.
    • FooBarWidget5 hours ago
      It says state. Copy on write still means it&#x27;s O(number of page table entries) even if you don&#x27;t copy the contents. It&#x27;s a well known issue that forking a program with large virtual memory size is slow.
      • mort964 hours ago
        It says &quot;(including memory)&quot;. It&#x27;s pretty natural to read this as &quot;(including the contents of allocated pages)&quot;.
      • m00x3 hours ago
        On modern hardware a cow page copy should only take 1-5ms. Redis forks to save the db to disk and it&#x27;s been a solid design choice.<p>I guess it depends on how sensitive your application is to main thread pauses.
        • trumpdong3 hours ago
          So like 1000-5000s if you have 4GB of data? Over an hour?
  • uecker6 hours ago
    The elegance of the fork() + exec() model is that every kind of configuration can be done after the fork using all the usual APIs. Every attempt to replace it with a combined call that I have seen so far seemed fundamentally poorer because it needs to add all configuration options as parameters to the call and then do this in away that you can extend it later and does not become a mess.
    • amluto5 hours ago
      I have the entirely opposite opinion. IMO a big mistake of the UNIXy model is that so much state is preserved across the creation of a process. For example, there are APIs to have a specific thing be fd number 4 so you can run a program and have it find that thing at fd 4. This is <i>weird</i>.<p>Windows, for all its many, many faults, did not use fork+exec and instead mostly has options for how one creates a process. It wasn’t done elegantly, but it was the right decision.
      • uecker4 hours ago
        Well, a lot of the power of the UNIX shell comes form this and I see this as a major advantage over Windows. So no, I do not think Windows got it right.<p>Any kind of replacement should aim for the same conceptual simplicity and power. Sadly, I fear that people driving development nowadays are more interested in building unbreakable walled gardens for advertisement or app stores, or trying to squeeze down the some small gain when used on the cloud. I am more interested in general computing on the user side.
        • dcrazy5 minutes ago
          Nothing about the UNIX shell is reliant on the fork model. Windows processes have stdio handles as well.
      • __david__4 hours ago
        Having fd 4 mean something specific is no weirder than having fds 0,1, and 2 mean something specific, which is probably never going to change. At some point you just gotta embrace the Unix.
        • JdeBP4 hours ago
          Heh! The Unix didn&#x27;t embrace the idea of file descriptor 3 meaning something specific. (-:<p>* <a href="https:&#x2F;&#x2F;jdebp.uk&#x2F;FGA&#x2F;bernstein-on-ttys&#x2F;cttys.html" rel="nofollow">https:&#x2F;&#x2F;jdebp.uk&#x2F;FGA&#x2F;bernstein-on-ttys&#x2F;cttys.html</a><p>Interestingly, on MS&#x2F;PC&#x2F;DR-DOS file descriptor 3 was stdaux. and file descriptor 4 was stdprn.
      • 17186274405 hours ago
        Is it weirder, that you can pass an variable precisely into argument 4? You do need to pass information to a subprocess and there needs to be some agreement on what means what. Sure, maybe you could use names instead of fds, but that sounds needlessly complicated.
        • amluto5 hours ago
          A way to pass a defined list of handles to a subprocess (or a friendly other process) makes sense. Having that mechanism be direct inheritance of those handles with the same numbering as the source is obnoxious.
        • jonhohle5 hours ago
          That’s like saying you could use positions to specify function argument access (as in assembly) instead of variable names. File descriptors being numbers that are likely array indexes in a file handle seems like a leaky abstraction. Having a namespace that a parent process share with its children seems like a much cleaner design.
      • chasil4 hours ago
        Well, Cygwin and Busybox have shown me that fork-heavy activities are about 100x slower on Windows than Linux.<p>The Windows approach may be correct, but it suffers in performance from the POSIX perspective.<p>I have heard that WSL1 iimproves this.
        • amluto4 hours ago
          Linux has worked pretty hard to optimize fork(). This doesn’t mean that fork() is a good idea.<p>Windows does not historically depend on fork(), so there was no native fork(), so Cygwin kludged it up.
          • JdeBP4 hours ago
            Actually, there <i>is</i> a native fork. There had to be, as POSIX personality support was a part of the Windows NT 3.1 design. What there wasn&#x27;t was a <i>Win32</i> form of fork. The <i>Native</i> API for Windows NT allowed it quite straightforwardly.
      • burnt-resistor5 hours ago
        You&#x27;re simply failing to grasp the value of the simplicity, compatibility, and portability of POSIX&#x2F;*nix. Inventing yet another way to create a process would be complex and break things. It&#x27;s a-la-carte to enable configuration after fork of the new CoW or non-CoW process but before exec (unless vfork or similar were used). This is the model.<p>If you want to greenfield re-engineer the world with all new system calls and a totally different execution model, feel free to go right ahead.
        • wvenable4 hours ago
          &quot;The reasonable man adapts himself to POSIX: the unreasonable one persists in trying to adapt the POSIX to himself. Therefore all progress depends on the unreasonable man.&quot;<p>― George Bernard Shaw, probably.
    • jcranmer3 hours ago
      Calling that elegant is a path dependence of the history of fork+exec.<p>In an alternative world where fork+exec never existed, a lot of those &quot;usual APIs&quot; would probably have had an explicit pid argument to them that let you modify process configuration from a different process. (This is how Fuschia works, e.g.). There&#x27;s a lot of benefit to this world: the most obvious is that you don&#x27;t have to magic up some IPC system just to report configuration errors, but there&#x27;s actually a good amount of utility in being able to have a manager process that is tweaking attributes of its children (e.g., debuggers would love it).
      • trumpdong2 hours ago
        Or you could call ptrace_syscall (that doesn&#x27;t currently exist) on your child processes that you are tracing because you&#x27;d always be tracing them by default, or get an io_uring for the child process, or...
        • uecker2 hours ago
          A ptrace_syscall would be interesting and would seem to be a full replacement for having the pid argument everywhere.<p>But frankly, I am not really seeing the value.
      • uecker2 hours ago
        Weren&#x27;t there enough parallel paths of development in this world?
    • pjc502 hours ago
      The flip side of this is that you have to be aware of the entire state of the process, including everything done in libraries, in order to correctly start a new process.<p>Quick, what&#x27;s the highest numbered open file descriptor in the your program?<p>This gets even worse if you have multiple threads running. Without looking it up, what is the state of all the various synchronization primitives in a forked process?
    • trumpdong3 hours ago
      It should be spawn, configure, exec. Configure can be done if the process starts with a ptrace attachment and no threads, so you can force it to do syscalls. Linux doesn&#x27;t even <i>have</i> a concept of &quot;process with no threads&quot;, so it&#x27;d probably have to have a dummy thread.
    • __david__5 hours ago
      I agree. I think the current way is very nice to use (in c). I think the best way would be to have something similar to vfork() but not bound by posix rules. Then make the normal posix apis (close, setuid, etc.) act like the Rust “builder” pattern. Possibly giving them a prefix for explicitness. That way the “fill out a giant structure” people could have their wish and the people that just want a faster posix experience don’t have to learn an entirely new concept and api surface. It would be future extensible that way, too (just add more prefixed calls to the builder).
    • fanf25 hours ago
      Yeah. The right way to eliminate fork() is to make the usual APIs that modify process state take an explicit process handle, so the same APIs can be used to set up an empty process. They can also be composed in other ways, eg for IPC or debugging.
    • matheusmoreira3 hours ago
      The new system calls described in the article have an extensible declarative command interface built into them to do things like close or duplicate file descriptors. Not opposed to it but it definitely stood out to me.
    • garaetjjte5 hours ago
      That&#x27;s mostly papering over design mistake that most syscalls doesn&#x27;t accept target pid. Otherwise you could just create suspended process, configure it with syscalls that explicitly take target pid, and start it.
      • uecker4 hours ago
        Maybe, I am not saying fork() + exec() model couldn&#x27;t be improved, but most people saying it is &quot;terrible&quot; and it needs to die seem to go on to propose something substantially worse.
      • trumpdong2 hours ago
        Or have a syscall that runs any other syscall in a different process.
    • PaulDavisThe1st3 hours ago
      Whatever elegance fork(2) has (or doesn&#x27;t) have, clone(2) has more.
  • jcalvinowens5 hours ago
    It is a weirdly common misconception that that fork() is cheap... it is O(N) on the size of the process, and it always has been.<p>Yes, it&#x27;s copy on write... but there is a linear relationship between the size of the process and the number of page table entries required to represent it.
  • ComputerGuru6 hours ago
    I&#x27;m not surprised Chen&#x27;s patch was rejected; that&#x27;s an extremely niche usecase not worth supporting. With my shell developer hat on, I agree with the closing &quot;developers would likely welcome a native implementation that isn&#x27;t (unlike the current implementation) hiding fork() and exec() under the covers&quot;.
    • smj-edison6 hours ago
      It sounds like they&#x27;re interested in the concept though, just not that specific implementation.
      • sanderjd6 hours ago
        Yeah this seems like a promising discussion.
  • ajkjk4 hours ago
    Fork always seemed conceptually terrible even when I first learned about it.. If you want to do one thing (start a process) you should not have to use a mysterious incantation that does a different unrelated thing (forks your process) in order to do it.<p>I am curious about what the best way to handle the example in the article of one process spawning many git subprocesses is. Surely it just doesn&#x27;t make sense to repeatedly start git from scratch in the course of a long-running parent operation. What&#x27;s the low cost abstraction for the same result, though?
    • kps16 minutes ago
      Fork is conceptually simple. Without bringing in any other layers, you start a process with the one thing known to exist: yourself.<p>Otherwise you need multiple steps to create a process, fill it with something to run, and arrange for it to execute. Or like Win32 you permanently smush them together with other layers, like filesystems and object loaders and linkers.
    • spacechild11 hour ago
      Yeah, as someone who originally came from Windows, the fork+exec model never made sense to me. Now I know it&#x27;s just a historical quirk, but for some reason there are still people who pretend that fork+exec is actually a good thing...
    • wmf4 hours ago
      libgit2 exists. You could imagine communicating with some gitd over a pipe&#x2F;socket but I don&#x27;t know why that would be a good idea. Short of that you have to spawn processes.
      • trumpdong2 hours ago
        On Windows maybe it would be a COM server, using IPC built into the OS. The client sees it like a local function call.
  • codedokode3 hours ago
    The problem with replacing exec&#x2F;fork is that you usually want to configure new process: for example, set up signal handlers, close or open FDs, switch namespaces, setup seccomp, adjust permissions. And all the system calls to do it apply only to the current process and you need something to replace them. The proposal in the article was to create a new API for this.<p>My idea is that we could make a new syscall, for example &quot;spawn&quot;, that creates a new empty process, loads some lightweight &quot;loader&quot; into it, and passes arbitrary configuration data. The loader configures the process and exec()&#x27;s the main program. This allows to avoid forking the memory and keep existing APIs, but still requires to fork file descriptors and other things.
    • nyrikki3 hours ago
      Luckily someone with a time machine saw your post and added it to POSIX.1-2001 :)<p>(Sorry if you weren&#x27;t joking) but yes, posix_spawn() has been a thing and in glibc fork is just a alias to clone()<p>Not exactly that OP idea, but fork&#x2F;exec is legacy really.
  • ktpsns6 hours ago
    There is lots of discussion on this old API here on hacker news, for instance <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=31739794">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=31739794</a>
  • ggm3 hours ago
    Aesthetically I have no intention of moving beyond. I&#x27;m content with my kernels scheduler and how it maps &quot;heavyweight&quot; processes to cores.<p>I do use threaded code. It&#x27;s significantly harder to write and reason about. (45 years in to a CS career, ageing out)<p>You have to be clever to do better than clever people. Clever people bootstrapped me into fork()&#x2F;exec() and I know my limits.
    • redleader553 hours ago
      When cores start needing more than 9 bits to be represented and RAM is in terabytes, many of the old assumptions need to change. Schedulers need to be implemented in userspace, RAM needs to be allocated in GB, not in 4k, io needs to require less round-trips between kernel and user space and NICs need to do a lot more work before the data reaches the CPU.
      • skydhash3 hours ago
        Does it need to be the same OS? Most consumer device are in the low 16GB range for memory with some outliers in the 64 and 128 GB. 32 cores are still in the realm of specialized devices.<p>Yes, we’re not the one paying for Linux development, but its subsystems are so complicated for general purpose computing. Like fitting formula 1 car parts onto a camry.
        • tadfisher2 hours ago
          Our software is littered with the consequences of these kinds of assumptions, and they have an impact on consumer use cases.<p>x86 still runs in real mode on boot despite dropping the PC BIOS.<p>Lots of software still assumes a 4kb page size, to the point where migrating Android to 16kb is an ongoing multi-year effort involving far too many people. And this is an OS for phones, which you might assume would lack the memory to benefit from a larger page size.<p>And one of the most popular consumer CPUs for enthusiasts, the Ryzen X3D chips, broke assumptions in both Linux and Windows schedulers that all cores have access to the same amount of L3 cache.<p>I would probably not assume the kinds of hardware limitations that we have now will persist into the useful lifetime of current software. Splitting the OS into &quot;consumer&quot; and &quot;enterprise&quot; variants is one of those moves that would bake in a <i>ton</i> of assumptions and make things messier in the future.
          • skydhash2 hours ago
            It’s all about contracts. It’s fine to define assumptions and build software on top of those. It’s also fine to break those and adjust the software. The trap is trying to steer towards a universal solution (Yagni is the cure there) or trying to slip something in that does not respect the contracts (hence bugs).<p>UEFI could have supported something like ELF and do away with real mode. Intel and Amd could have just introduced a new line of cpu and everyone could have transitioned to that (with maybe shims to soften the change). But everyone is all about backwards compatibility and compile once, runs for eternity.
    • skydhash3 hours ago
      I’m using Emacs and various cli tools and while threads are nice to have, they can easily ramp up the complexity of a program beyond what is necessary. I much prefer the boilerplate of setting up a thread pool and tasks queue, rather than dealing with all the await&#x2F;async syntactic sugar.
  • Panzerschrek4 hours ago
    The whole approach of using <i>fork</i> seems to be unnatural for me. In many cases (even in the majority of them) it&#x27;s not needed to inherit the whole structure of the parent process, but to start a given executable. Windows does this better with its <i>CreateProcessW</i> interface.
  • asveikau3 hours ago
    The things you can do between fork and exec are sometimes underestimated. Off the top of my head, you can call dup2(), you can set a process group id, probably a few other things.<p>If you contrast that with win32, where you optionally pack a bunch of initial values into a struct, win32 is a much more narrow, less pleasant, less freeform interface, where it is harder to introduce more features.<p>But I think there is already posix_spawn to imitate that philosophy on Unix-like OSs.
    • dcrazy2 hours ago
      posix_spawn is emulated on Linux, but it is a native syscall on macOS (and possibly other OSes?). As discussed in the linked article, there is interest in changing Linux to adopt this model, where posix_spawn is its own fundamental primitive.
      • asveikau2 hours ago
        Yeah, I think it is a reasonable transition path or implementation detail for some systems to implement it in userland atop fork(2), and others to natively spawn a new process without copying the old address space.
    • loeg2 hours ago
      &gt; The things you can do between fork and exec are sometimes underestimated. Off the top of my head, you can call dup2(), you can set a process group id, probably a few other things.<p>What do you mean underestimated? You can do <i>anything</i> between fork and exec; there are no limitations.
      • asveikau2 hours ago
        That&#x27;s not true. Just one example, if you do anything with threads you are pretty screwed. For example if another thread holds a mutex at the time of fork(2), and you also want that mutex.
        • loeg1 hour ago
          You can create threads in forked children before exec. Nothing in the kernel prevents you from invoking clone().<p>You&#x27;re talking about libc (glibc) implementation details now; userspace programs running on the Linux kernel do not have to be implemented in C or use glibc&#x27;s primitives. Your earlier comment I initially replied to was talking about kernel syscalls. Forked processes are free to invoke any syscall they want, not just dup2 or a handful of others.
          • asveikau31 minutes ago
            I&#x27;m not talking about glibc implementation details. I&#x27;m talking about how mixing fork(2) with threads creates harmful race conditions.<p>The forked child has only 1 thread in its process. If the parent&#x27;s threads are holding a lock or are in the middle of mutating a shared data structure, you&#x27;re fucked, because those threads are no longer running in your child&#x27;s copy of the address space and will not finish their work. This issue is fundamental to how threads work and what fork(2) does.
            • loeg8 minutes ago
              Again, you&#x27;re talking about userspace now. Not kernel-imposed constraints. A userspace program is always free to deadlock itself; fork doesn&#x27;t change that.
      • dcrazy2 hours ago
        That’s not true. man 7 signal-safety
        • loeg1 hour ago
          You&#x27;re talking about libc design choices, not constraints imposed by the kernel. To the kernel, a post-fork pre-exec process is just any old process. GP was suggesting post-fork processes were constrained in the <i>syscalls</i> they could invoke; they are not.
          • asveikau19 minutes ago
            I did not say they are constrained in what syscalls they can make, as if some nanny at the syscall entry point will punish you for doing wrong. I said that it interacts poorly with threads due to inherent race conditions. See the other comment.
            • loeg7 minutes ago
              &gt; I said that it interacts poorly with threads due to inherent race conditions.<p>No, you absolutely did not: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=48427396">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=48427396</a><p>Literally nothing in that comment mentions or discusses threads.<p>&gt; I did not say they are constrained in what syscalls they can make<p>You wrote: &quot;The things you can do between fork and exec are sometimes underestimated. Off the top of my head, you can call dup2(), you can set a process group id, probably a <i>few</i> other things.&quot;<p>Those are all syscalls. You can also invoke any of the other ~hundreds of syscalls linux exposes, not only dup2, setpgid, and a &quot;few&quot; others.
  • trumpdong3 hours ago
    I liked the other proposal where you can create a blank process and then force it to make syscalls, ending with execve. That doesn&#x27;t require a bunch of special data structures to hold the syscalls you want to do.
  • debatem16 hours ago
    There are a lot of slightly different fork-exec-like things in the concept space and it&#x27;s hard to imagine one approach satisfying them all. IMO it would be interesting to take an approach analogous-ish to sched_ext_ops where you built the rough flow chart of a combined fork-exec, but with hooks built to enable ebpf to change behavior or skip the bits these sophisticated users don&#x27;t want&#x2F;need.
    • MBCook5 hours ago
      Fork&#x2F;exec is great if you actually want the traditional copy of your process for some reason.<p>For launching something totally new, like the example in the article of some tool calling git, I think it does make a ton of sense to make something new.<p>Especially since I suspect that is by far the more common case. I suspect “I want a clone of me“ is relatively rarely used at this point.
      • debatem115 minutes ago
        Relatively rarely, but in some performance sensitive use cases. Mine happens to be fuzzers, where a very cheap fork-like primitive would be a really big win.
  • mike_hock5 hours ago
    The most astonishing part is that this is dated June 5th, 2026.<p>I.e. a year that starts with 20, not 19.
    • JdeBP4 hours ago
      These discussions were definitely had back in the 20th century too. The spawn model versus the fork+execve model has been an on-going debate since the time of MS&#x2F;PC&#x2F;DR-DOS.
  • Sophira6 hours ago
    I&#x27;m guessing that a big part of the problem with moving away from fork() in general is that each new process needs a copy of the parent process&#x27; environment anyway, right?
    • zerobees6 hours ago
      The LWN article is incorrect in saying that it &quot;must copy the entire process state (including memory) for the child process&quot;. There are some kernel structures and page tables that need to be initialized, plus you need a new stack, but it&#x27;s not nearly as dramatic as implied. Most of the parent&#x27;s memory is &quot;incorporated by reference&quot;, so to speak.<p>In fact, if you profile it, in the fork() + execve() model, execve() is far more expensive, because not only does it replace the old process with a new one, but it also involves running the dynamic linker, which opens, parses, and mmaps library files.<p>It still makes sense to get rid of the fork() overhead if you&#x27;re going to throw away the cloned process state soon thereafter, but if you wanted to make process execution radically faster, rethinking the exec architecture would probably offer more significant gains.
      • corbet5 hours ago
        The kernel does not copy every page, but it does have to copy all of the VMAs. Setting memory to COW (which can involve changing a lot of page-table-entries) is not free either. I guess I could have mentioned copy-on-write explicitly, but I do not believe that what I wrote was incorrect.
      • nasretdinov5 hours ago
        Fork becomes more and more expensive the higher the RSS of the process, roughly 1ms per 1Gb of the process size with 4kb pages. Given that modern servers can easily support 1-2Tb of RAM the fork() part can easily take several hundred milliseconds, blocking everything in the meantime. So for larger programs you kinda have to have a &quot;fork helper&quot; process if you need to execute external programs for some reason.
    • sanderjd6 hours ago
      A lot of times you actively don&#x27;t want the parent environment or any of the memory or file descriptors. And then you have to actively do work to fix all that stuff up after the fork.
    • dijit6 hours ago
      I&#x27;m a bit naive, but I don&#x27;t <i>think</i> that&#x27;s necessarily a requirement.<p>It might be commonly held convention, and thus, an assumption, in Linux (and, broadly, UNIX) but I don&#x27;t think it&#x27;s true inside VAX or even Windows, so I don&#x27;t think it&#x27;s a <i>requirement</i>.<p>Unless I&#x27;ve missed something (which is totally possible, this is not an area of OS design I&#x27;ve spent much time).
      • lanstin5 hours ago
        But also UID, groups, controlling TTY, process group, capabilities, pipes, shared memory, etc. and the file descriptors while maybe not inherently needed are how a lot of Unix plumbing works.
      • sjmulder6 hours ago
        Even DOS has environment inheritance!
    • lokar6 hours ago
      the environment is not that big
  • lokar6 hours ago
    This seems unnecessary to me. In the example, the core of git should be a library yo can link so you don&#x27;t need to run the binary. That would be better in every way.
    • 17186274405 hours ago
      But when you use a process, you get tons of things for free, the subtask is invoked in parallel, you get isolation and you can control execution for free. Unless you are already writing a multithreaded program or already accept passing objects in memory, using a process is actually easier to write than using a library.<p>If I use a library, I also need to start using threads and need to invent some core synchronization mechanism. I essentially are reinventing a small scheduler, when I already get this from the OS for free. Also know any crash in the third-party code will crash the whole program, the third-party code has access to the whole address space. With invoking a process you also have a standardized API implemented by the OS.
      • lokar35 minutes ago
        I&#x27;m not sure what you mean by inventing a sync mechanism, all languages come with one. Same with a scheduler, either your language runtime or the OS (or both) will deal with scheduling.
    • omoikane4 hours ago
      Launching git repeatedly was probably not the best example. But it&#x27;s hard to think of good examples where launching processes repeatedly is the most performant thing to do, probably because launching processes had been expensive and everyone has learned to do something else (libraries, zygotes, etc). Maybe a different question is: if launching processes were cheap, is there something we would implement as processes instead of libraries?<p>I can recall just one program that&#x27;s intentionally not implemented as a library, but I think people have since built a library on top of it:<p><a href="https:&#x2F;&#x2F;dechifro.org&#x2F;dcraw&#x2F;#:~:text=Why%20don%27t%20you%20implement%20dcraw%20as%20a%20library" rel="nofollow">https:&#x2F;&#x2F;dechifro.org&#x2F;dcraw&#x2F;#:~:text=Why%20don%27t%20you%20im...</a>
    • sanderjd6 hours ago
      There are lots of reasons to want to spawn fresh processes, which aren&#x27;t solved by linking a library.
      • lokar5 hours ago
        Sure, but not many times a second
        • kllrnohj5 hours ago
          Every build system ever says hello.
        • sanderjd1 hour ago
          Why not?
      • aerzen5 hours ago
        Spawning processes should not be on the hot path of any program.
        • 17186274405 hours ago
          Why? That&#x27;s a very useful processing primitive.
          • lokar5 hours ago
            It’s a hack with many disadvantages. Sometimes a hack is the right answer, but the kernel should it add a primitive for it.
            • sanderjd1 hour ago
              Aren&#x27;t we discussing just such a primitive?
            • MBCook5 hours ago
              Should bash link in every program the user might want? Load them up as dynamic libraries?
        • pizlonator5 hours ago
          It ends up on the hot path of programs that use process isolation aggressively
  • a-dub3 hours ago
    i thought this was all fixed with special modes of clone that are optimized and don&#x27;t actually copy anything (ie, it creates a new deficient process that can pretty much only exec)?
  • burnt-resistor5 hours ago
    &gt; &quot;If you are repeatedly creating large processes, you are already doing it wrong. The fix is in user space, not the kernel.&quot;<p>Every couple of years, someone claims they have &quot;the solution&quot; implying everyone else who came before them didn&#x27;t know what they were doing.
    • yxhuvud4 hours ago
      It can also mean that neither the hardware side or the software side is static, but change over time. That means that their demands and what they allow also change over time. This leads to the insight that what was perhaps a good idea on 70s hardware&#x2F;software is not necessarily a good, or even ok, idea 50 years later on modern hardware executing OSes and programs that have been kept up to date.
  • hparadiz6 hours ago
    Maybe tangentially related but I always think it&#x27;s silly that every linux process has the same libgcc_so.so.1 loaded into memory for each process even though the raw binary for the library is exactly the same so you end up with like 800 copies of libgcc_so.so.1 in memory.<p>I mean maybe this has been optimized for already and I don&#x27;t know what I&#x27;m talking about but maybe someone with more knowledge about the kernel knows? Is this something we simply can&#x27;t optimize for because of security implications?
    • 2019846 hours ago
      Shared libraries (and mmapped files in general) are deduplicated; it&#x27;s nowhere near as bad as you think. The kernel loads a .so into memory once and then maps that memory into every process that mmaps it.<p>Editing to add: this deduplication is one of the greatest upsides to dynamic linking. Common libs like libgcc and libc only have to exist in memory once and can stay in CPU caches, whereas if they were statically linked into every binary, each binary would have a copy of that library that wouldn&#x27;t be shared with anything else and you&#x27;d waste a lot of memory.
      • sjmulder6 hours ago
        Doesn&#x27;t the loaded code have to be patched for relocations?
        • ptspts5 hours ago
          It does, so not 100% is reused. The patched parts are in different sections though, so the entire .text (code) section ends up being reused.
        • monocasa5 hours ago
          Not on modern archs that provide decent support for PIE (position independent executables).
          • 2019844 hours ago
            How do you think position independent code can call functions from other .so&#x27;s without being patched with their addresses?<p>They can&#x27;t, so even PIC code still has to have a relocation table that gets patched. It&#x27;s in a different page than the code though, so code does still get reused.
            • monocasa4 hours ago
              That&#x27;s not really patching though, any more than any use of function pointers is patching.
              • 2019843 hours ago
                There&#x27;s a part of the .so ELF file (the Global Offset Table aka GOT) that has to be modified with all the addresses of the functions being imported, which of course vary from process to process.<p>If not patching, what exactly would you call modifying part of the file?
                • monocasa2 hours ago
                  And the got is just a big table of pointers like any other table of pointers your application manipulates as it runs.<p>This isn&#x27;t meant as a reductive take, but instead that there is a difference between completely describable in C like the contents of the .got section, and something like a .reloc section that actually has to understand the generated assembly in order to build the relocation table to load and link the executable. Both are linking, but I&#x27;ve saved &quot;patching&quot; for more brain surgery esque techniques. Like on mips, the jump instruction immediate is the bottom 26 bits of the absolute address of the target, so you&#x27;re going through and modifying all of the jump instructions if you load it to somewhere it wasn&#x27;t linked at.
        • t-35 hours ago
          Not if it&#x27;s position-independent.
    • saidinesh56 hours ago
      Typically libgcc_so.so is loaded by the linker, which uses an mmap call to map the binary into the address space.<p>&gt; The kernel keeps track of which file is mapped where, and can detect when a request is made to map an already mapped file again, avoiding physical memory allocation if possible.<p>Relevant stack overflow answer: <a href="https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;61950951&#x2F;linux-shared-library-loading-and-sharing-the-code-with-other-process#61956768" rel="nofollow">https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;61950951&#x2F;linux-shared-li...</a>
    • mlaretallack6 hours ago
      In Linux, when a shared lib is loaded by multiple processes, its loaded once and not duplicated in ram. Only if a memory page is modified by the process will the memory be duplicated. (Hope I have explained that correctly)
    • monocasa6 hours ago
      Those mappings by default all go to the same shared memory.<p>Unices have been sharing executable memory between processes longer than there&#x27;s been mmap for user space to do the same thing themselves. I remember seeing it in the 2BSD kernel for instance.
    • BoingBoomTschak6 hours ago
      Eh? Aren&#x27;t shared libraries actually <i>shared</i> in memory?
      • 17186274405 hours ago
        Yeah, that&#x27;s kind of the point.
        • johnthescott1 hour ago
          shared libraries does not imply shared in ram only.
    • sirsinsalot6 hours ago
      I have a rule for myself. If I think something is silly or stupid, I assume I don&#x27;t understand it. I usually find I do not understand it, and it no longer seems silly when I do understand it.<p>In this case too, you think it is silly because you don&#x27;t understand it. Your assumptions are wrong, making it seem silly.