`posix_spawn` 的能力

capability of `posix_spawn`

我正在编写一个小程序,它有点像一个服务器,它产生它的客户端程序(在本地,而不是通过网络)并在它们之间做一些有趣的事情。虽然我使用的主要 OS 是 Linux,但我希望它在其他 OS 上 运行,包括 Windows。有 forkexec 可以完成这项工作,但是当我通过 cygwin 将程序移植到 Windows 时,我不希望在 cygwin 中实现的那个糟糕的 fork 踢in,它实际上调用 CreateProcess 并使用 setjmp/longjmp 和共享内存互斥锁将当前进程的内存区域复制到新进程,所有这些都是为了被另一个程序替换( exec)。在阅读 cygwin 的 FAQ 页面时,我发现 spawn.h 及其 posix_spawn,基本上看起来像 windows 中的 CreatePorcess(Ex)。这似乎是一个新功能(...我的意思是不是原始的 UNIX 系统功能之一),所以我对此有一些疑问。

  1. 实施得好、广泛吗? (我在网上看到一些帖子说his/her系统下没有定义。)

  2. 使用 posix_spawn 代替 Linux 中的 fork/exec 是否可以提高或降低性能?

  3. 为什么 posix_spawnfork/exec 更鲜为人知,也更少使用,尽管自 1999 年以来一直是标准?

根据Linux man pages,它出现在 2000 年发布的 glibc 2.2 版中,该实现符合 POSIX.1-2001 和 POSIX.1-2008。我希望它至少在任何至少使用这个 glibc 版本的平台上得到支持,因为它的行为至少可以在这些平台上用 fork + exec 来模拟。

在 Linux 上,如果使用 vfork 而不是 fork

,您可能会期望在 fork/exec 上有轻微的性能改进

The child process is created using vfork(2) instead of fork(2) when either of the following is true:

  • the spawn-flags element of the attributes object pointed to by attrp contains the GNU-specific flag POSIX_SPAWN_USEVFORK; or
  • file_actions is NULL and the spawn-flags element of the attributes object pointed to by attrp does not contain POSIX_SPAWN_SETSIGMASK, POSIX_SPAWN_SETSIGDEF, POSIX_SPAWN_SETSCHEDPARAM, POSIX_SPAWN_SETSCHEDULER, POSIX_SPAWN_SETPGROUP, or POSIX_SPAWN_RESETIDS.

In other words, vfork(2) is used if the caller requests it, or if there is no cleanup expected in the child before it exec(3)s the requested file.

  1. Is it implemented well, widely? (I saw some posts on the internet that it is not defined under his/her system.)

高级实时 XSI 选项组是可选的,因此您可以符合 POSIX,但不实施它。但是对于 GNU/Linux,您现在可以放心使用它了。

  1. Can I expect any performance improvement or deterioration by using posix_spawn instead of fork/exec in Linux?

可能是的,对于大型进程来说 quite some time could be spent copying page tables only to be discarded at exec time. Implementations of posix_spawn like musl's or glibc's use vfork(2) (or clone(2) directly) when possible in order to avoid this. For systems like cygwin, fork is emulated 成本相当高 posix_spawn 大大减少了开销。

  1. Why is posix_spawn less known and less used than fork/exec although being standard since 1999?

我猜是惯性。

posix_spawn 广泛实施,但您应该尽可能使用它。

  • 如果平台缺少它,使用 drop-in 替代品总是很容易 fork-and-exec.

  • 如果 "native"/最佳实现可用(作为系统的一部分,或作为 drop-in platform-specific 的一部分),它将产生很大的影响对于 fork 昂贵的系统的差异,对于根本不能 fork 的系统的差异更大(MMU-less 系统,Windows 没有像 cygwin 这样的东西,等)。

  • 即使在 fork 是本机和 "fast" 的系统上,如果 parent 有很多虚拟映射,它仍然会相当慢,并且它是温和的即使对于小 parent,也比最佳 posix_spawn 慢。有关一些发现,请参阅此 Twitter 线程:https://twitter.com/RichFelker/status/602313644026761216

至于为什么它没有更广泛地使用 used/implemented,可能是因为不为人所知,而且相当笨拙,无缘无故地 object-oriented API 设计。