Given the PID of the process, you need to know the number of processes for which this PID is a PPID .
How to do this with the ps utility (or some other).
ps -h --ppid 1 | wc -l Keys ps: -h without a header (whatever the process does not count), --ppid processes with the given ppid. The output of ps is given by wc , which can read lines.
To get the number of all descendants recursively, you can use pstree and conjure a little:
pstree -p 1 | grep -oP '\(\d+\)' | tail -n +2 | wc -l pstree draws the process tree starting at the specified. Unfortunately, the tree is too beautiful and it is not convenient to count it. The -p switch gives pid processes in parentheses on the tree. We select these brackets with grep. We skip the first line of tail , since this is the process with which we started. And finally consider. But errors are possible if there is a process in the system called the one numbers in parentheses (which is unlikely in principle)
Since the label is C, then it may be useful to someone a program that solves this problem for the entire descendant tree of a given process.
Let's take as a basis the list of PPID pairs, PID of all processes, received by the commandps -e -o ppid,pid
and sort it by PPID value. Thus, all the descendants of each process will be close.
Find in this list all direct descendants of a given process (i.e., those pairs in the list whose PPID is equal to the specified PID) and alternately perform the same search for each of them (we will bypass the "wide" process tree). To implement the steps of our search, we use the PID queue, in which we place the found direct descendants.
The result (the number of descendants of the specified process) will be equal to the number of elements placed in the queue (extracted from it), minus the specified process that initializes the queue to traverse the tree.
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <errno.h> int main (int ac, char *av[]) { pid_t inipid = atoi(av[1] ? : "0"); if (kill(inipid, 0) && errno == ESRCH) exit((puts("No such process"), 1)); // сортируем по ppid, таким образом все потомки одного pid окажутся рядом FILE *in = popen("ps -e --no-headers -o ppid,pid | sort -n -k 1", "r"); if (!in) exit((perror("ps ..."), 2)); int ppasize, nppa = 0; // количество пар ppid,pid (всего процессов из ps -e) struct pids { pid_t ppid, pid; } *ppa = (__typeof__(ppa))malloc(sizeof(*ppa) * (ppasize = 100)); if (!ppa) exit((perror("malloc"), 2)); // прочтем отсортированный по ppid набор ppid,pid в ppa[] while (fscanf(in, "%d %d", &ppa[nppa].ppid, &ppa[nppa].pid) == 2) if (++nppa == ppasize) if (!(ppa = (__typeof__(ppa))realloc(ppa, sizeof(*ppa) * (ppasize *= 2)))) exit((perror("realloc"), 2)); pclose(in); /* Пройдем по дереву потомков inipid и подсчитаем их число. Для этого используем очередь. Для pid из головы очереди ищем в ppa[] все процессы с таким ppid (это непосредственные потомки) и помещаем их в хвост очереди. Повторяем, пока в очереди что-то есть. Количество элементов выбранных из очереди является ответом (-1 inipid) */ pid_t q[nppa + 1]; // очередь потомков inipid int qh = 0, qt = 0, // индексы head и tail очереди nchilds = -1; // наш result q[qt++] = inipid; // инициируем процесс поиска, занеся в очередь inipid // повторяем, пока очередь не станет пустой do { nchilds++; pid_t pid = q[qh++]; // новый parent int first = 0, last = nppa, mid; // используем binsearch для поиска первого потомка (ppa[i].ppid == pid) while (first < last) { mid = first + (last - first) / 2; // такое вычисления middle позволяет избегать overflow в общем случае if (pid > ppa[mid].ppid) first = mid + 1; else last = mid; } // переберем всех потомков pid и занесем их в очередь // они расположены последовательно, поскольку мы сортировали ppa[] по ppid while (first < nppa && pid == ppa[first].ppid) q[qt++] = ppa[first++].pid; } while (qh < qt); free(ppa); return printf("pid %d has %d childs (of %d total pids)\n", inipid, nchilds, nppa) < 0; } PS
Type __typeof__ for malloc / realloc through __typeof__ done so that the program is also translated with C ++ by the compiler.
Counting all descendants of the process:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define MAX_SIZE 300 int countProc(int pid) { int count = 0; char cmd[MAX_SIZE]; FILE *fd; sprintf(cmd, "ps -o %%p --ppid %d", pid); fd = popen(cmd, "r"); fscanf(fd, "%*s"); int id; while(fscanf(fd, "%d", &id) != EOF) { count++; count += countProc(id); } pclose(fd); return count; } int main(int argc, char *argv[]) { if(argc != 2) { printf("Error!\n"); return 1; } int pid = atoi(argv[1]); int count = countProc(pid) + 1; printf("%d\n", count); return 0; } Source: https://ru.stackoverflow.com/questions/636008/
All Articles
sum(1 for _ in process.children()), but the heading about the "subtree" says:sum(1 for _ in process.children(recursive=True)), whereprocess = psutil.Process(pid)(Python language). Edit the question and specify what result you want. It’s not quite clear why [c] is a label if you call external utilities. - jfs