> I would like to know if there is a way to limit CPU usage of a process and its child.
> I used setrlimit with RLIMIT_CPU, but all child process inherit from the same value as the parent.
>
> If I limit a process P0 to 2s, and P0 fork() 2 children (P1 and P2), P1 and P2 will have 2 new seconds of cpu time too.
> I would like a global CPU time for all my process from P0 and not 2s for each.
>
> A fork bomb can easily eat all CPU with this method. (I know that I can limit the number of process, but this is not the same usage).
>
> Is there a way to control this ?
There is no way to limit the total aggregate CPU usage of a process
and all its children, except by setrlimit(RLIMIT_CPU, ...) which has
the property that you describe: Each descendant gets the same limit,
which is not decreased by prior and/or subsequent CPU usage by "kin"
in the same group [setpgrp] of processes.
> Or is it possible to limit CPU per user instead of per process ?
No. There is an infinite supply of time: just wait, and more time appears.
Therefore the OS concentrates on mediating the ongoing fraction of time
that is available to a process group.
The 'nice' command (also system call) sets scheduling priority,
and can be used [in advance] to enhance significantly the
probability that some other process (at greater scheduling
priority [lower numerical "nice" value]) will be able to quell
a fork() bomb. The "nice" value is the "NI" column in the
output of "ps l".
Using the feature of "control groups" which is rather new (a year or so),
it might be possible to write an custom kernel extension to do as you wish.
But fork() bombs are not a serious problem: their creators get banned.
--