看着这篇文章,我不明白 Kaylum 的回答。我有两个问题。
1)她/他想使用变量“count”来计算从一个fork产生的进程总数(即子孙等+原始进程的总数)。我看到他/她首先在父进程中将计数设置为 1,这很有意义(计算父进程),但随后他/她在子进程中再次将计数设置为 1。为什么这有意义?Count 已经设置为 1,这只会再次将 count 设置为 1。
count += WEXITSTATUS(status);
2)我一直在调查 WEXITSTATUS 并且据我所知,它通过退出返回进程的退出状态。我的问题是我必须使用
exit(0)
或者
exit(1)
或其他让它工作的东西。这方面的文档不清楚。换句话说,它可以作为 Kaylum 的
为方便起见,此处的完整代码段:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t before_pid, after_pid;
pid_t forked_pid;
int count;
int i;
int status;
before_pid = getpid();
count = 1; /* count self */
for (i = 0; i < 3; i++) {
forked_pid = fork();
if (forked_pid > 0) {
waitpid(forked_pid, &status, 0);
/* parent process - count child and descendents */
count += WEXITSTATUS(status);
} else {
/* Child process - init with self count */
count = 1;
}
}
after_pid = getpid();
if (after_pid == before_pid) {
printf("%d processes created\n", count);
}
return (count);
}