環境:Vmware Workstation;CentOS-6.4-x86_64
程序要求:
編寫一個孤兒進程,這個孤兒進程可以創建100個僵死進程。
分析:
1、首先在一個進程中fork,創建兩個完全一樣的進程。
2、退出父進程,使子進程成爲孤兒進程。
3、在孤兒進程中循環創建進程,並結束孫子進程,使子進程成爲僵死進程。
實現步驟:
1、創建並編輯源文件main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char *args[])
{
// 在程序中fork,創建兩個一樣的進程
pid_t id = fork();
// 判斷fork是否成功
if (id == -1)
{
// 輸出出錯信息
printf("fork failed : %s\n", strerror(errno));
}
// 結束父進程,使子進程成爲孤兒進程
if (id > 0)
{
exit(0);
}
// 執行子進程的代碼
else
{
// 創建循環變量
int i = 0;
for(; i < 100; i++)
{
// fork產生孫子進程
pid_t temp_id = fork();
// 判斷fork是否成功
if (temp_id == -1)
{
// 輸出出錯信息
printf("fork failed : %s\n", strerror(errno));
}
// 執行孫子進程的內容
if (temp_id == 0)
{
// 退出孫子進程,使子進程成爲僵死進程
exit(0);
}
}
// 在子進程退出之前,讓其暫停
// 否則,子進程退出的話,僵死進程和孤兒進程也就沒法實現了
pause();
}
return 0;
}
2、創建並編輯文件makefile:
.SUFFIXES:.c .o
CC=gcc
SRCS=main.c
OBJS=$(SRCS:.c=.o)
EXEC=main
start: $(OBJS)
$(CC) -o $(EXEC) $(OBJS)
@echo "-----------------------------OK-----------------------"
.c.o:
$(CC) -Wall -o $@ -c $<
clean:
rm -rf $(EXEC) $(OBJS)
3、編譯並執行程序:
[negivup@negivup mycode]$ make
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ ./main
4、查看進程信息:
[negivup@negivup ~]$ ps -aux
negivup 16249 0.0 0.0 3916 136 pts/1 S 19:21 0:00 main 根據這個號殺死進程
negivup 16250 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16251 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16252 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16253 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16254 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16255 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
negivup 16256 0.0 0.0 0 0 pts/1 Z 19:21 0:00 [main] <defunct>
......
可以看出,已死進程剛好100個,也就是說,僵死進程有100個。 5、回收僵死進程以及孤兒進程:
[negivup@negivup ~]$ kill 16429 殺死進程
negivup 4997 0.0 0.0 97860 1792 ? S 08:16 0:02 sshd: negivup@pts/
negivup 5701 0.0 0.1 108440 1916 pts/1 Ss+ 09:10 0:00 -bash
negivup 14849 0.0 0.0 108328 1864 pts/0 Ss 18:03 0:00 -bash
postfix 14916 0.0 0.1 78800 3252 ? S 18:07 0:00 pickup -l -t fifo
root 16365 0.0 0.0 100900 564 ? S 19:22 0:00 sleep 60
negivup 16367 2.0 0.0 110232 1144 pts/0 R+ 19:23 0:00 ps -aux
會發現,程序中沒有僵死進程了。
PS:根據傳智播客視頻學習整理得出。