Monthly Archives: April 2023

Pitfalls with fork() in real-time contexts

This thread went viral. The main takeaways:

  • After calling fork(), a parent process gets its entire address space write protected to facilitate COW. This causes page faults.
  • This makes fork() unsafe to call from anywhere in a process with realtime deadlines โ€” including non realtime threads! Usually non RT can do what they want, but that is an interesting exception.
  • On modern glibc, system() doesn’t use fork(), it uses posix_spawn(). But is posix_spawn() safe from a non RT thread?
  • posix_spawn() doesn’t COW โ€” the parent/child literally share memory โ€” so the page fault issue doesn’t apply. However the parent is suspended to prevent races between the child and parent. This seems RT unsafe…
  • However, only the caller thread of the parent is suspended, meaning the RT threads are not suspended and continue running with no page faults.
  • So it is safe to use system() or posix_spawn() from a non RT thread.