signal fork execl

  

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


void sig_int(int signo)
{
    printf("pid [%d] interrupt by [%d].\n", getpid(), signo);
    fflush(stdout);
}

int main(int argc,char *argv[])
{
    char buf[MAXLINE];
    pid_t pid;
    int status;

    signal(SIGINT,sig_int);

    if((pid=fork()) < 0) perror("fork error");

    else if (pid==0) {
        for(;;) sleep(5);
        // execlp("./t.sh",  (char *)0,  (char *) 0);
    }

    if((pid==waitpid(pid,&status,0))<0) perror("waitpid error.");

    printf("status = [%d].\n", status);
}

 

Notes:  when above program is execed. Press Ctrl+^ will cause sig_init was called twice.

One for parent, one for child process.

 

 

//

 

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


void sig_int(int signo)
{
    printf("pid [%d] interrupt by [%d].\n", getpid(), signo);
    fflush(stdout);
}

int main(int argc,char *argv[])
{
    char buf[MAXLINE];
    pid_t pid;
    int status;

    signal(SIGINT,sig_int);

    if((pid=fork()) < 0) perror("fork error");

    else if (pid==0) {
        // for(;;) sleep(5);
        execlp("./t.sh",  (char *)0,  (char *) 0);      // t.sh is a shell script, it only sleep loop.

    }

    if((pid==waitpid(pid,&status,0))<0) perror("waitpid error.");

    printf("status = [%d].\n", status);
}

 

Notes:

When above program is execed, if ctrl + ^ is pressed, sig_int will be called only once.

It is only called by parent program.

since child process call execlp, it will cover old handler for SIG_INT, recover to its default

handler,  which will cause process termination. That says, child process will by terminated by

SIG_INT signal.

Therefore, the parent will also exit, after waitpid return.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值