I wrote the following C program to limit the maximum processes this program can create (on Linux). This program uses setrlimit(), and it is expected that this program can create at most 4 processes.
// nproc.c
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
int main(void)
{
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 4;
setrlimit(RLIMIT_NPROC, &rlim);
for (int i = 0; i < 3; ++i) printf("%d\n", fork());
sleep(1);
return 0;
}
When I compiled and ran this program as a normal user, it gave the following output:
$ ./nproc
-1
-1
-1
-1 indicates that fork() failed and rlimit was working properly to limit maximum processes that a program can create. But when I ran this program as root, it gave the following output:
$ sudo ./nproc
25926
25927
25928
0
0
25929
0
25930
25931
0
0
0
25932
0
We can see that all the fork() succeeded and rlimit was not working properly. Where is the problem?
the following proposed code:
wait()orwait_pid()for each child process started.sleep(1)keeps the output nice and organized. However, during thatsleepthe child complete and exits, so there is actually only 1 child process running any at any one time, so even if the call tosetrlimit()had been successful, that 'fork()` loop could have run forever.and now, the proposed code:
a run of the program results in:
which indicates a problem with the call to
setrlimit()from the MAN page:
so, the call to
setrlimit()is limiting the number of threads, not the number of child processesHowever, if we add a couple of print statements immediately after the call to
getrlimit()and again after the call tosetrlimit()the result is:then the result is:
which indicates that call to:
setrlimit()did not actually change the limits for child processesNote: I'm running ubuntu linux 18.04