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.

 

你可能感兴趣的:(signal fork execl)