previous on process:
linux进程创建可以使用fork和vfork
进程在创建后有三种命运:
destiny one:正常情况
此时子进程先于父进程死亡,父进程调用wait或者wait_pid为其收尸。
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/unistd.h>
extern int errno;
int main()
{
pid_t pid;
if((pid = fork()) < 0)
{
printf("fork return error %s\n", strerror(errno));
exit(-1);
}
else if(pid == 0)
{
printf("child process is deading!\n");
exit(0);
}
if(wait(0) != pid)
{
printf("wait error %s\n", strerror(errno));
}
system("ps -o pid,ppid,stat,command");
printf("parent process is going dead!\n");
exit(0);
}
destiny two:成为僵尸进程
在子进程介绍后父进程没有为其收尸
include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
extern int errno;
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("fork return error %s\n", strerror(errno));
exit(-1);
}
else if(pid == 0)
{
printf("this could be a zombie process!\n");
_exit(0);
}
else
{
system("ps -o pid,ppid,stat,command");
printf("parent process dead!\n");
}
exit(0);
}
如果父进程是守护进程则需要对这种情况进行处理,zombie会占用系统一定的资源,当zombie进程过多后会照成系统性能下降,不是daemon程序倒是无所谓,因为还有init进程可以收拾它
destiny three:被init收监
在子进程退出之前父进程就结束了运行,那么这个时候init会成为该子进程的父进程
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
extern int errno;
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("fork return error %s\n", strerror(errno));
exit(-1);
}
else if(pid == 0)
{
sleep(1);
printf("make sure parent is dead\n");
_exit(0);
}
else
{
system("ps -o pid,ppid,stat,command");
printf("parent is go away!\n");
}
exit(0);
}