系统编程-进程-守护进程、孤儿进程、僵尸进程

 

1. 守护进程

 

 

2. 孤儿进程

父进程结束,子进程就成为了孤儿进程。孤儿进程由1号进程(init进程)领养。

 

2.1实验: 

实验思路: 先产生一个孤儿进程,然后打印出该孤儿进程的父进程ID。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h> // exit(0)

int main(){

	int i=0;

	printf("before fork : pid: %d,  ppid: %d
",  
		                 getpid(), getppid());	
		
	pid_t pid = fork();			
	if(pid < 0){
		perror("fork ");

	}else if(0 == pid){
		sleep(3);

	}else{
		exit(0);
        }

	printf("pid: %d,  ppid: %d
",  
                         getpid(), getppid());	

	while(1);
	printf("pid: %d 
",  getpid());

	return 0;
}

  

2.1.1. ubuntu上编译运行

孤儿进程的父进程是init进程,即ID号为1的进程啊, 这里怎么是1673(upstart)进程? 百度下

经过百度,可以理解为: 在ubuntu内,upstart进程就是init进程。

 

2.1.2 嵌入式linux板子上运行:

 

小结: 孤儿进程的父进程是init进程, init进程的进程ID一般是1。 ubuntu上的init进程是sbin/upatsrt, 其进程ID不是1。

 

3. 僵尸进程及其避免方法

 

3.1 实验:

实验思路: 先产生一个僵尸进程, 然后在另一个终端内执行: ps -aux | grep process_name ,  观察该进程是否为僵尸进程。

                   同时测试杀死僵尸进程的方法。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h> // exit(0)

int main(){

	int i=0;

	printf("before fork : pid: %d,  ppid: %d
",  
		                 getpid(), getppid());	
		
	pid_t pid = fork();			
	if(pid < 0){
		perror("fork ");

	}else if(0 == pid){
		printf("pid: %d,  ppid: %d
",  
                         getpid(), getppid());	
        	exit(0);
	}

	while(1);

	return 0;
}

在一个ubuntu的终端内编译运行:

在另一个ubuntu终端内查看、验证该进程的僵尸状态

可见 12132进程是R,即运行态。 而12133是Z,即僵尸态。

接着,我们来测试杀死该僵尸进程的方法

测试1

小结: 使用kill -9 直接去杀僵尸进程 , 无法杀死。

测试2

此时已不存在ab内含有僵尸进程的信息。 所以僵尸进程已经被杀死。Ps: 这个12225 --color=auto不知道是啥信息,ubuntu上有这类信息了,不管他了,这不重要。

小结:杀死僵尸进程的父进程,可以达到杀死僵尸进程的目的。

.

/************* 社会的有色眼光是:博士生、研究生、本科生、车间工人; 重点大学高材生、普通院校、二流院校、野鸡大学; 年薪百万、五十万、五万; 这些都只是帽子,可以失败千百次,但我和社会都觉得,人只要成功一次,就能换一顶帽子,只是社会看不见你之前的失败的帽子。 当然,换帽子决不是最终目的,走好自己的路就行。 杭州.大话西游 *******/
原文地址:https://www.cnblogs.com/happybirthdaytoyou/p/14478179.html