关于c:防止在子进程中分叉

Prevent forking in a child process

我有一个 Linux 进程(C 程序),它产生了几个子进程。我想在系统级别禁止在这些子进程中进行另一个分叉,这样如果这些进程无论如何尝试分叉,它们就会被杀死。如何做到这一点?我更喜欢将此策略嵌入到主机 C 代码中。 setrlimit(2) 可以吗?


是的,setrlimit() 可以做到这一点。请参阅手册页并阅读

RLIMIT_NPROC
The maximum number of processes (or, more precisely on Linux, threads) that
can be created for the real user ID of the calling process. Upon encountering this
limit, fork(2)
fails with the error EAGAIN.

或者,您可以使用 /etc/security/limits.conf 对进程设置硬限制。在文件中查找一些示例。

1
2
3
4
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0