1.孤儿进程(没有父进程的子进程)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();//再创建一个进程
if(pid > 0)
{
printf("%d是父进程\n", getpid());
sleep(1);
}else if(pid == 0)
{
printf("%d是子进程\n", getpid());
for(int i=0; i<7; i++)
{
printf("这是一个孤儿进程\n");
sleep(1);
}
}else
{
printf("创建失败\n");
}
return 0;
}
测试结果
ubuntu@ubuntu:day4$ gcc hm.c
ubuntu@ubuntu:day4$ ./a.out
55159是父进程
55160是子进程
这是一个孤儿进程
ubuntu@ubuntu:day4$ 这是一个孤儿进程
这是一个孤儿进程
这是一个孤儿进程
这是一个孤儿进程
这是一个孤儿进程
这是一个孤儿进程
ubuntu@ubuntu:day4$ ps -ajx
1 55160 55159 55078 pts/2 55078 S 1000 0:00 ./a.out
55125 55161 55161 55125 pts/3 55161 R+ 1000 0:00 ps -ajx
2.僵尸进程(子进程被杀死,“”尸体“”未回收)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();//再创建一个进程
if(pid == 0)
{
printf("%d是子进程\n", getpid());
sleep(1);
}else if(pid > 0)
{
printf("%d是父进程\n", getpid());
for(int i=0; i<7; i++)
{
printf("这是一个僵尸进程\n");
sleep(1);
}
}else
{
printf("创建失败\n");
}
return 0;
}
测试结果
ubuntu@ubuntu:day4$ gcc hm.c
ubuntu@ubuntu:day4$ ./a.out
55496是父进程
这是一个僵尸进程
55497是子进程
这是一个僵尸进程
这是一个僵尸进程
这是一个僵尸进程
这是一个僵尸进程
这是一个僵尸进程
这是一个僵尸进程
ubuntu@ubuntu:day4$ ps -ajx
55444 55496 55496 55444 pts/1 55496 S+ 1000 0:00 ./a.out
55496 55497 55496 55444 pts/1 55496 Z+ 1000 0:00 [a.out] <