如何显示创建的进程数?
(不使用公式)
for (i=0; i<3; i++)
fork();
count = count + 1;
printf("%d",count);
解决方法:
有很多方法可以做到这一点,一种好的技术是让每个孩子将一个字节写入文件描述符,原始进程可以读取该文件描述符.请注意,为简洁起见,以下代码绝对不包含任何错误检查.此外,我们仅报告生成的进程数(7),而不是对原始进程进行计数以得出8:
int main(void) {
int fd[2];
int depth = 0; /* keep track of number of generations from original */
int i;
pipe(fd); /* create a pipe which will be inherited by all children */
for(i=0; i<3; i++) {
if(fork() == 0) { /* fork returns 0 in the child */
write(fd[1], &i, 1); /* write one byte into the pipe */
depth += 1;
}
}
close(fd[1]); /* exercise for the reader to learn why this is needed */
if( depth == 0 ) { /* original process */
i=0;
while(read(fd[0],&depth,1) != 0)
i += 1;
printf( "%d total processes spawned", i);
}
return 0;
}