Chinaunix首页 | 论坛 | 博客
  • 博客访问: 626003
  • 博文数量: 121
  • 博客积分: 8469
  • 博客等级: 中将
  • 技术积分: 1065
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-03 10:32
文章分类

全部博文(121)

文章存档

2013年(1)

2012年(15)

2010年(2)

2009年(8)

2008年(95)

我的朋友

分类: LINUX

2008-08-19 11:27:03

#include
#include
#include
void new_op(int,siginfo_t*,void*);
int main(int argc,char**argv)
{
   struct sigaction act;
    int sig;
    pid_t pid;        
    
    pid=getpid();
    sig=atoi(argv[1]);   
   
    sigemptyset(&act.sa_mask);
    act.sa_sigaction=new_op;
    act.sa_flags=SA_SIGINFO;

    if(sigaction(sig,&act,NULL)<0)//安装信号
    {
        printf("install sigal error\n");
    }
    if(fork()==0)//创建子进程
    {
        union sigval sv;
        sv.sival_int = 66;
        printf("child pid is %d\n", getpid());
        while(1)
        {
        sleep(1);
        sigqueue(getpid(), sig, sv);//子进程向自己发信号
        }
    }
    while(1)
    {
        sleep(2);
        printf("wait for the signal\n");
    }

}
void new_op(int signum,siginfo_t *info,void *myact)//信号处理函数
{
    printf("pid is %d the int value is %d \n", getpid(), info->si_int);
}
输出:
child pid is 21309
pid is 21309 the int value is 66
wait for the signal
pid is 21309 the int value is 66
pid is 21309 the int value is 66
wait for the signal
pid is 21309 the int value is 66
pid is 21309 the int value is 66
wait for the signal
pid is 21309 the int value is 66
pid is 21309 the int value is 66
信号处理函数中打印的进程号和子进程是一致的,子进程继承了父进程对信号的处理。

再来看看fork系统调用的说明:   

功能描述:
建立一个子进程。所建立的子进程PID 和 PPID不同于其父进程,同时资源使用被设置为0,文件锁和挂起的信号不被继承。
Linux内部,fork的执行使用copy-on-write页面,所以耗费的资源只是拷贝父进程页表,建立唯一子进程task结构体的时间和内存。

其中提到了挂起的信号不被继承,哪什么是挂起的信号呢?已经生成但还未被传递的信号被称为挂起的信号。

在进程的task_struct结构中有关于本进程中未处理信号的数据成员:
struct sigpending pending:
struct sigpending{
struct sigqueue *head, **tail;
sigset_t signal;
};
其中head和tail是信号队列的指针,挂起的信号就是已经添加到信号队列里,但还没有处理的信号。


参考资料
http://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html
http://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index2.html
阅读(3114) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~