| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 4755 人关注过本帖
标题:sigaction() 的一例
只看楼主 加入收藏
madfrogme
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
结帖率:98.63%
收藏
 问题点数:0 回复次数:0 
sigaction() 的一例
信号这种东西,说再多都是零,看代码慢慢领悟了

程序代码:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

void sig_chld(int); /* prototype for our SIGCHLD handler */

int main(void) {
    struct sigaction act;
    pid_t pid;
    
    /* Assign sig_chld as our SIGCHLD handler */
    act.sa_handler = sig_chld;

    /* We don't want to block any other signals in this example*/
    sigemptyset(&act.sa_mask);

    /* 
     * We're only interested in children that have terminated,
     * not ones which have been stopped(eg user pressing 
     * control-Z at terminal)
     */
    act.sa_flags= SA_NOCLDSTOP;

    /*
     * Make these values effective. If we were writng
     * a real application, we would probably save
     * the old value instead of passing NULL.
     */
    if( sigaction(SIGCHLD, &act, NULL) < 0) {
        fprintf(stderr, "sigaction failed\n");
        return 1;
    }
    
    /* Fork */
    switch(pid = fork()) {
        case -1:
            fprintf(stderr, "ford failed\n");
            return 1;
        case 0:         /* child-- finish straight away */
            _exit(7)    /* exit status = 7 */
        default:        /* parent */
            sleep(10);        /* give child time to finish */
    }
    return 0;
}

/*
 * The signal handler function -- only gets called when
 * a SIGCHLD is received, ie when a child terminate
 */

void sig_chld(int sigo) {
    int status, child_val;
    
    /* Wait for any child without blocking */
    if(waitpid(-1, &status, WNOHANG) < 0) {
        /*
         * calling standard I/O functions like
         * fprintf() in a signal handler is not 
         * recommended, but probably OK in 
         * toy programs like this one.
         */
        fprintf(stderr, "waipid failed\n");
        return;
    }
    
    /*
     * We now have the info in 'status' and 
     * and manipulate it using the macros in 
     * wait.h.
     */
    if(WIFEXITED(status)) {
        child_val = WEXITSTATUS(status);
        printf("child's exited normally with status %d\n", child_val);
    }
}


程序执行结果就是立刻显示
child's exited normally with status 7


[ 本帖最后由 madfrogme 于 2012-8-10 20:50 编辑 ]
搜索更多相关主题的帖子: void only example include 
2012-08-10 19:45
快速回复:sigaction() 的一例
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015073 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved