7

In a small script I have, I'm starting a shell and then setting RLIMIT_NPROC on it to some small number, like 5, using prlimit

Then, I try to execute a shell script that only contains:

#!/bin/bash
echo hi
sleep 3

by sending "./test.sh\n" through stdin and waiting for the result. At the same time, I'm using ps --ppid <somepid> -o pid= to list the child PIDs of the first.

This always fails with the error bash: fork: retry: No child processes. I've tried setting the limit to RLIM_INFINITY to see how many child processes are created, but only one is listed (naturally the shell processing test.sh).

How can I properly limit the number of child processes (or more generally, restrict some sort of fork bomb)? I know about cgroups and other similar alternatives, but I'm trying to write this to learn, and this behavior really confuses me.

I think it might be due to RLIMIT_NPROC's documentation stating that it limits "The maximum number of processes (or, more precisely on Linux, threads)" and large numbers of threads being created, but the program only works once I increase RLIMIT_NPROC up to 500 or so, and that doesn't seem very reasonable.

If this behavior is unexpected, it might be a coding error, in which case I'll try to clean up the testing code to post on here.

2 Answers 2

6

RLIMIT_NPROC does not control the number of children that a process can have.

It controls the total number of processes that user can have. More specifically, as it is a per process setting, when fork(), clone(), vfork(), etc is called by a process, the RLIMIT_NPROC value for that process is compared to the total process count for that process's parent user, not to the number of children that process has.

1

I understand the man page for getrlimit(2) as saying that it limits the number of threads (not relevant here) that can run as the real user.

I'm not sure I understand what you are doing, so bear with me. You start a program that takes the script you list, and runs that as a child. Meanwhile you run ps to check for PIDs?

The shell the user is running is certainly one, the program launching the script another, then there is the script running, and ps makes 5. If now ps tries to launch a thread for its own internal purposes, it will fail due to the limit to 5 processes.

What you describe looks like some kind of experiment to see how to do something. What problem are you really trying to solve? Without knowning what that is, there really is no way for us to suggest better alternatives (or tell you how to do what you want).

1
  • What I posted is exactly what I'm trying to do ;) I'm trying to set RLIMIT_NPROC. setprlimit applies to the process I specify the PID of (the child) and not to the parent script, ps, etc., so that shouldn't be the problem. Thanks for answering, still confused by this. Jan 27, 2013 at 6:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .