正常程序:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
printf("this is main pid=%d, ppid=%d\n", getpid(), getppid());
pid_t pid = fork();
if(pid < 0)
{
printf("fork error=%s\n", strerror(errno));
return -1;
}
else if(pid == 0)
{
printf("0:this is child pid=%d, ppid=%d\n", getpid(), getppid());
}
else
{
printf("%d:this is father pid=%d, parent=%d\n", pid, getpid(), getppid());
printf("wait begin\n");
waitpid(pid, NULL, 0);
printf("wait end\n");
getchar();
}
return 0;
}
执行结果:
僵尸程序:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
printf("this is main pid=%d, ppid=%d\n", getpid(), getppid());
pid_t pid = fork();
if(pid < 0)
{
printf("fork error=%s\n", strerror(errno));
return -1;
}
else if(pid == 0)
{
printf("0:this is child pid=%d, ppid=%d\n", getpid(), getppid());
}
else
{
printf("%d:this is father pid=%d, parent=%d\n", pid, getpid(), getppid());
/*printf("wait begin\n");
waitpid(pid, NULL, 0);
printf("wait end\n");*/
getchar();
}
return 0;
}
执行结果:
父进程结束后僵尸子进程自动结束。
孤儿程序:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
printf("this is main pid=%d, ppid=%d\n", getpid(), getppid());
pid_t pid = fork();
if(pid < 0)
{
printf("fork error=%s\n", strerror(errno));
return -1;
}
else if(pid == 0)
{
printf("0:this is child pid=%d, ppid=%d\n", getpid(), getppid());
getchar();
printf("0:this is child pid=%d, ppid=%d\n", getpid(), getppid());
}
else
{
printf("%d:this is father pid=%d, parent=%d\n", pid, getpid(), getppid());
}
return 0;
}
执行结果: