0

I'm running a program with multiple forks based on entered number for an assignment and I would like to get the number of processes that the system will let me create prior to forking so I can print and error message and stop the program rather than trying to fork my way through until -1.

Is there a way to do this in C?

rxj
  • 39
  • 1
  • 11
  • 1
    You can process output of `ps aux`, for example. – Over Killer May 03 '14 at 11:09
  • Possible duplicate of http://stackoverflow.com/questions/9361816/maximum-number-of-processes-in-linux. – Chnossos May 03 '14 at 11:12
  • possible duplicate of [Maximum number of threads per process in Linux?](http://stackoverflow.com/questions/344203/maximum-number-of-threads-per-process-in-linux) – P.P May 03 '14 at 11:16

2 Answers2

2

You can get the number processes limit for the current user using getrlimit. Have a look at man getrlimit for more details.

#include <sys/resource.h>

rlim_t max_processes_for_current_user(void) {
   struct rlimit rlp;
   getrlimit(RLIMIT_NPROC, &rlp);
   return rlp.rlim_max;
}

But to know if you will be able to create a new process you also need to figure out how many processes the current user is already running. Also there is a race condition between you checking the limit and number of current processes and you forking a new one. Also you can run into the global limit.

Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57
1

I think you can use getrlimit() for resource type RLIMIT_NPROC. For more information on the system call you can look into the man page of getrlimit.

praks411
  • 1,972
  • 16
  • 23