相关函数:
fork();
NAME
fork - create a child process
SYNOPSIS
#include <unistd.h>
pid_t fork(void);
wait();
NAME
wait, waitpid, waitid - wait for process to change state
SYNOPSIS
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
编程思路:
先通过fork();创建两个进程,避免子进程或父进程成为僵尸进程,运用wait()函数,等待子程序的资源自动释放,在父进程下嵌套两次创建两次进程。
编程代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
pid_t id = fork();
if (id == -1)//创建进程失败,返回值-1
{
perror("fork id failed!");
return -1;
}
else if (id > 0) // 父进程的空间
{
printf("world\n");
wait(NULL);//等待子程序释放资源
pid_t id1 = fork(); // 在父进程下在创建两个进程
if (id 1== -1)
{
perror("fork id1 failed!");
return -1;
}
else if (id1 > 0)
{
wait(NULL);
pid_t id2 = fork();
if (id2 == -1)
{
perror("fork id1 failed!");
return -1;
}
else if (id2 > 0)
{
printf("end\n");
}
else if (id2 == 0)
{
sleep(1);
}
}
else if (id1 == 0)
{
printf("start\n");
}
}
else if (id == 0) // 子进程的空间
{
printf("hello\n");
}
return 0;
}
运行结果: