fork() 和 排列组合

fork() 和 排列组合

起因

在学操作系统,有一个题建立了几个进程.于是就投机取巧,在return 0前面加printf

经过

玩的时候就试了一下别的方式,比如

//fig_331.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    
    
	pid_t pid;
	int depth=0;
	for(int i=0;i<5;++i) {
    
    
		pid=fork();
		if(pid)wait(NULL);
		else {
    
    
			++depth;
		}
	}
	printf("%d\n",depth);
	return 0;
}
gcc fig_331.c
./a.out | sort | uniq -c

结果

结果是 1,4,6,4,1,有点吃惊,不过仔细一想,一共fork了四次,其中有n次为子进程的可能性当然就是 C 4 n C_4^n C4n.

猜你喜欢

转载自blog.csdn.net/agctXY/article/details/119120370