我使用C / C ++在Linux上编程。我有一个问题,我试图找到一个函数或东西,以获得父进程中的子进程数。
请帮助我,谢谢
我不确定POSIX是否为此定义了一个函数,但你总是可以自己在全局变量中计算它们,只需在父项的每个fork之后加1,并在子项上将其设置为0。
int globalVariable = 0;
main() {
pid_t pID = fork();
if (pID == 0) { //child
globalVariable = 0;
cout << "Child Process" << end;
}
else if (pID < 0) { //failed to fork
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else { // parent
cout << "Parent Process:";
++globalVariable;
}
}
使用procfs
:计算/proc/[mypid]/task
中的目录数量,并获得启动的子进程数。
有关更多信息,请参阅proc(5)。
您可以使用带有--ppid选项的'ps'命令列出所有子进程,然后使用wc -l对它们进行计数
ps --ppid | wc -l
以下是如何在C ++ 11中完成它,如果需要,可以很容易地适应预C ++ 11或C.您需要检查系统中的每个进程,看看它的父进程是谁:
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <string>
#include <fstream>
using std::string;
using std::ifstream;
using std::to_string;
bool is_number(const string& s) {
string::const_iterator it = s.begin();
for (; it != s.end() && isdigit(*it); ++it) {
}
return !s.empty() && it == s.end();
}
int count_children(const pid_t pid) {
DIR* dir;
if ((dir = opendir("/proc"))) {
int num_children = 0;
for (struct dirent* ent; (ent = readdir(dir));) {
if (is_number(ent->d_name)) {
ifstream ifs(string("/proc/" + string(ent->d_name) + "/stat").c_str());
string word;
for (int i = 0; i < 4; ++i) {
ifs >> word;
}
if (word == to_string(pid)) {
++num_children;
}
}
}
closedir(dir);
return num_children;
}
perror("could not open directory");
return INT_MAX;
}
父进程中另一个可能的选项是在父进程中创建一个初始化为零的变量,并在每次收到SIGCHLD时每次分叉和递减时递增它。