标题: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



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-375055-1-1.html




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

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