Chinaunix首页 | 论坛 | 博客
  • 博客访问: 72534
  • 博文数量: 19
  • 博客积分: 485
  • 博客等级: 下士
  • 技术积分: 154
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-25 17:14
文章分类
文章存档

2013年(1)

2012年(10)

2011年(8)

分类: LINUX

2012-05-29 12:19:25

P O S I X定义
孤儿进程组:该组中每个成员的父进程要么是该组的一个成员,要么不是该组所属会话的成员。
一个进程组不是孤儿进程组条件是,该组中有一个进程其父进程在属于同一个会话的另一个组中。

GNU解释了为什么会提出孤儿进程组的概念:

When a controlling process terminates, its terminal becomes free and a new session can be established on it. (In fact, another user could log in on the terminal.) This could cause a problem if any processes from the old session are still trying to use that terminal.
To prevent problems, process groups that continue running even after the session leader has terminated are marked as orphaned process groups.
When a process group becomes an orphan, its processes are sent a SIGHUP signal. Ordinarily, this causes the processes to terminate. However, if a program ignores this signal or establishes a handler for it, it can continue running as in the orphan process group even after its controlling process terminates; but it still cannot access the terminal any more.

1,POSIX上说孤儿进程组与父进程有关,而GNU上说孤儿进程组与控制进程有关,这怎么理解?
2,shell是控制进程,他的父进程是init进程(不和shell在一个session里面),是不是shell所在的进程组(假设就包含一个shell进程)是孤儿进程组?


示例程序
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include



static void sig_hup()
{
printf("%s:::process id ==%d , parent id ==%d\n",__FUNCTION__,getpid(),getppid());
}
static int print_pid(const char *ptr)
{
int pgid=getpgrp();
printf("%s:::%s:::process id ==%d ,parent id ==%d,group pid==%d\n",__FUNCTION__,ptr,getpid(),getppid(),pgid);
if(-1==pgid){
perror("getpgid:");
}
}
int main(int argc, char *argv[])
{
int ret=0;
pid_t pid=fork();
if(0>pid){
perror("fork:");
exit(-1);
}
else if(0==pid){
signal(SIGHUP, sig_hup);
print_pid("child");

kill(getpid(),SIGTSTP);

print_pid("child");
char buffer[10];
memset(buffer,0,10);
ret=read(STDIN_FILENO, buffer, 2);
if(-1==ret){
perror("read:");
sleep(2);
print_pid("child");
exit(-1);
}
printf("child::read content==%s\n",buffer);
sleep(3);
print_pid("child");
}
else{
sleep(3);
print_pid("parent");
exit(1);
}
}
运行结果:
 ./orphan_pg
print_pid:::child:::process id ==1867 ,parent id ==1866,group pid==1866
print_pid:::parent:::process id ==1866 ,parent id ==1348,group pid==1866
sig_hup:::process id ==1867 , parent id ==1
print_pid:::child:::process id ==1867 ,parent id ==1,group pid==1866
read:: Input/output error
print_pid:::child:::process id ==1867 ,parent id ==1,group pid==1866

总结:
定义孤儿进程组的目的是防止已脱离对话期的孤儿进程组与后续与此控制终端相关联的进程对同一控制终端操作而引起问题,因此系统将孤儿进程组设置成不可再使用控制终端(输入),这使上例中的子进程读标准输入时产生错误.系统对于处于停止状态的孤儿进程会发送SIG_HUP和SIG_CON这两个信号,
问题:若孤儿进程组确需要读控制终端,应该怎办,重新打开控制终端,还是新建对话期?


阅读(2355) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~