1

I am trying to use setrlimit to limit the number of processes a program can create. Here is my code:

struct rlimit limiter;
getrlimit( RLIMIT_NPROC, &limiter );
limiter.rlim_max = limiter.rlim_cur = 10;
setrlimit( RLIMIT_NPROC, &limiter );

int val = fork();
printf( "Error number %d\n", errno ); //gives 11
if( val == -1 ) {
    printf( "Fork failed\n" );
} else if( val ) {
    printf( "parent\n" );
} else {
    printf("child\n" );
}
return 0;

Since the value of rlim_max and rlim_cur is 10, my program should be allowed to fork 10 processes. But right now it is failing even for a single fork call. Though it works if I set the values to around 250. I don't understand why is that. I want a way to limit the number of forks to n.

rohan013
  • 199
  • 1
  • 1
  • 14
  • 2
    Does your user already have running processes that count towards the limit? – EOF Sep 18 '15 at 10:34
  • Well, I am running this program with the same user as the one I am logged in with, so yes i guess ? – rohan013 Sep 18 '15 at 12:57
  • Well, there you go. `man getrlimit/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.`. I guess you could create a separate user to execute your program? – EOF Sep 18 '15 at 13:00
  • I can do that, but it would still work incorrectly if the separate user starts another program. How could I limit the number of processes by started by _this_ program ? – rohan013 Sep 18 '15 at 14:04

0 Answers0