我有一个注册 atfork
处理程序(通过 pthread_atfork()
)的库,当 fork()
为叫。就我而言,我不需要 fork 环境可用,因为我只想在 fork()
之后调用 exec()
。因此,我想要 fork()
但没有任何 atfork
处理程序。那可能吗?我是否错过了任何重要的边缘情况?
最佳答案
您可以使用vfork()
(NPTL 实现不调用 fork 处理程序)。尽管 POSIX 已从标准中删除了 vfork
,但它可能在您的实现中可用。
Fork handlers established using pthread_atfork(3) are not called when a multithreaded program employing the NPTL threading library calls vfork(). Fork handlers are called in this case in a program using the LinuxThreads threading library. (See pthreads(7) for a description of Linux threading libraries.)
或者,posix_spawn()
。这与vfork
类似。手册页显示:
According to POSIX, it unspecified whether fork handlers established with pthread_atfork(3) are called when posix_spawn() is invoked. On glibc, fork handlers are called only if the child is created using fork(2).
或者,syscall
并直接使用SYS_clone
。 SYS_clone
是用于在 Linux 上创建线程和进程的系统调用号。因此,如果您立即执行,syscall(SYS_clone, SIGCHLD, 0);
应该可以工作。
syscall(SYS_fork);
(由 Shachar 回答)可能也会起作用。但请注意,SYS_fork 在某些平台上不可用(例如 aarch64、ia64)。 SYS_fork
在 Linux 中被认为是过时的,它只是为了向后兼容而存在,Linux 内核使用 SYS_clone 来创建所有“类型”的进程。
(注意:这些选项大多仅限于 glibc/Linux)。
关于c - fork+exec 没有 atfork 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810597/