gpt4 book ai didi

c - C 中是否有一种编程方式来确定 Linux 下一组进程中曾使用过的进程数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:28 26 4
gpt4 key购买 nike

我知道 sysinfo() 函数返回一个 procs 参数,表示当前在您的 Linux 系统上运行的进程总数。

但是,setrlimit()getrlimit() 函数的 RLIMIT_NPROC 参数限制了一个进程的子进程数可以有。

为了让系统强制执行该数字,我想它知道该 中的当前进程数。该号码是否易于访问?

最佳答案

为了强制执行 RLIMIT_NPROC 限制,linux 内核读取 copy_process 函数中的 &p->real_cred->user->processes 字段(在 fork() 例如) http://lxr.free-electrons.com/source/kernel/fork.c?v=4.8#L1371

 1371         if (atomic_read(&p->real_cred->user->processes) >=
1372 task_rlimit(p, RLIMIT_NPROC)) {

或在 sys_execve(do_execveat_common 在 fs/exec.c 中):

1504    if ((current->flags & PF_NPROC_EXCEEDED) &&
1505 atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) {
1506 retval = -EAGAIN;
1507 goto out_ret;

因此,如果 processes 大于 RLIMIT_NPROC,函数将失败。该字段定义为 struct user_struct 的一部分(通过 struct cred real_cred 中的 sched.h 访问为

 atomic_t processes;    /* How many processes does this user have? */

因此进程计数是按用户计算的。

copy_process 中的字段在失败时递减:

1655 bad_fork_cleanup_count:
1656 atomic_dec(&p->cred->user->processes);

字段的增量在copy_cred中:http://code.metager.de/source/xref/linux/stable/kernel/cred.c#313

313 /*
314 * Copy credentials for the new process created by fork()
315 *
316 * We share if we can, but under some circumstances we have to generate a new
317 * set.
318 *
319 * The new process gets the current process's subjective credentials as its
320 * objective and subjective credentials
321 */
322 int copy_creds(struct task_struct *p, unsigned long clone_flags)

339 atomic_inc(&p->cred->user->processes);

372 atomic_inc(&new->user->processes);

手册页说这是每个用户的限制:http://man7.org/linux/man-pages/man2/setrlimit.2.html

   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.

关于c - C 中是否有一种编程方式来确定 Linux 下一组进程中曾使用过的进程数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com