文章目录
1.创建一个孤儿进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid > 0)
{
printf("this is parent\n\n");
printf("this is parent : %d child:%d\n",getpid(),pid);
}else if(0 == pid)
{
sleep(1);
printf("this is child ppid:%d child:%d\n",getppid(),getpid());
}
else
{
perror("fork");
return -1;
}
return 0;
}
子进程的ppid为1,1是init进程 用于收养孤儿进程
2.创建一个僵尸进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid > 0)
{
printf("this is parent\n\n");
while(1)
{
printf("this is parent : %d child:%d\n",getpid(),pid);
sleep(3);
}
}else if(0 == pid)
{
while(1)
{
printf("this is child ppid:%d child:%d\n",getppid(),getpid());
_exit(0);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
Z是僵尸状态,子进程退出,但是父进程没有给该进程收尸