1. 创建一个进程链
创建一个进程链,每个进程创建一个子进程,子进程创建孙进程,如P1 --> P2 --> P3 --> P4
。
关键代码如下(未考虑fork失败的情况):
#define N 4
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main()
{
int i;
for (i=1; i<N; ++i)
if (fork()) break;
fprintf(stderr, "#%d is process %ld with parent %ld\n", i, (long)getpid(), (long)getppid());
}
2. 创建一个进程扇
一个进程创建若干子进程,形成一个进程扇,
关键代码如下(未考虑fork失败的情况):
#define N 4
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main()
{
int i;
for (i=1;i<N;++i)
if (fork()==0) break;
fprintf(stderr, "#%d is process %ld with parent %ld\n", i, (long)getpid(), (long)getppid());
}
3. 创建一个进程树
关键代码如下(未考虑fork失败的情况):
#define N 4
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main()
{
int i;
int id=0;
for (i=1; i<N; ++i)
if (fork()==0) id=i;
fprintf(stderr, "#%d is process %ld with parent %ld\n", id, (long)getpid(), (long)getppid());
}