使用 fork 显示循环中的进程数

Ali*_*ice 3 c linux loops fork for-loop

如何显示创建的进程数?
(不使用公式)

for (i=0; i<3; i++)
fork();
count = count + 1;
printf("%d",count);
Run Code Online (Sandbox Code Playgroud)

Wil*_*ell 5

有很多方法可以做到这一点,一个好的技术是让每个子进程将一个字节写入原始进程可以读取的文件描述符中。请注意,为简洁起见,以下代码绝对不包含错误检查。此外,我们只报告产生的进程数 (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;
}
Run Code Online (Sandbox Code Playgroud)