简体   繁体   English

如何限制子线程或子进程以限制在C中派生

[英]How to restrict child thread or a child process to restrict from forking in C

In C language,I have a child thread(using pthreads), Is there any way to restrict this child, so that we can't call fork inside this thread? 在C语言中,我有一个子线程(使用pthreads),有什么方法可以限制这个子线程,以便我们不能在该线程内调用fork?

If we write fork inside, program should not compile. 如果我们在内部编写fork,则程序不应编译。

I can also have a child process instead of child thread, as long as it cannot fork further. 我也可以有一个子进程而不是子线程,只要它不能进一步分叉。

Basically how can I have a child process or child thread, which cannot fork a process any further. 基本上,我如何拥有一个子进程或子线程,它们不能再分叉一个进程。

You can always try to play games with pthread_atfork : http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_atfork.html 您可以随时尝试使用pthread_atfork玩游戏: http : //pubs.opengroup.org/onlinepubs/009695399/functions/pthread_atfork.html

Basically, you can use pthread_atfork() to install a "child" callback which always calls exit() . 基本上,您可以使用pthread_atfork()安装一个始终调用exit()的“子”回调。 This way, your threads may still fork, but the forked process will exit immediately, so no harm will be done (and only a minimal overhead incurred). 这样,您的线程可能仍会分叉,但是分叉​​的进程将立即退出,因此不会造成任何危害(并且仅产生最小的开销)。

With processes it may be somewhat more complicated. 使用过程可能会更加复杂。 Linux allows you to limit a number of processes per user (so called RLIMIT_NPROC when set with setrlimit() ). Linux允许您限制每个用户的进程数(使用setrlimit()设置时称为RLIMIT_NPROC)。 When this limit is reached, no further forks are possible for a given user id. 达到此限制后,对于给定的用户标识,将无法再进行其他派生。 Thus, you can create a parent process with a CAP_SETUID capability and a dummy user, having the RLIMIT_NPROC set to 1. This way, you can fork from parent, change the child uid to that of the "limited" user you've created in advance and drop the CAP_SETUID capability. 因此,您可以创建一个具有CAP_SETUID功能和一个虚拟用户的父进程,并将RLIMIT_NPROC设置为1。这样,您可以从父进程派生,将子uid更改为在其中创建的“受限”用户的子uid。提升和降低CAP_SETUID功能。 At this point, child will have no possible way to fork itself. 此时,孩子将无法自行分叉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM