Thursday, August 25, 2011

POSIX Signal Sample C Code

/*

 * signal.c, communication between
 * child and parent processes using kill() and signal().
 * fork() creates the child process from parent. The pid can be checked to decide
 * whether it is the child (== 0) * or the parent (pid = child process id).
 * The parent can then send messages to child using the pid and kill().
 * The child picks up these signals with signal() and calls appropriate functions.
 * An example of communicating process using signals is signal.c:
 * signal.c --- Example of how 2 processes can talk
 * to each other using kill() and signal()
 * We will fork() 2 process and let the parent send a few
 * signals to it`s child
 * gcc signal.c -o signal
 */


#include <stdio.h>
#include <signal.h>

void sighup(); // routines child will call upon sigtrap
void sigint();
void sigquit();

int main() {
    int pid;
    /*
     * get child process
     */

     if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);
    }

    if (pid == 0) {              // child
        signal(SIGHUP,sighup);   // set function calls
        signal(SIGINT,sigint);
        signal(SIGQUIT, sigquit);
        for(;;);                 // loop for ever
    } else {                     // parent
    /*
     * pid hold id of child
     */

        printf("\nPARENT: sending SIGHUP\n\n");
        kill(pid,SIGHUP);
        sleep(3); /* pause for 3 secs */
        printf("\nPARENT: sending SIGINT\n\n");
        kill(pid,SIGINT);
        sleep(3); /* pause for 3 secs */
        printf("\nPARENT: sending SIGQUIT\n\n");
        kill(pid,SIGQUIT);
        sleep(3);
    }
    return 0;

}

void sighup(){ 
   signal(SIGHUP,sighup); /* reset signal */
   printf("CHILD: I have received a SIGHUP\n");
}

void sigint() {
    signal(SIGINT,sigint); /* reset signal */
    printf("CHILD: I have received a SIGINT\n");
}

void sigquit() {
    printf("My DADDY has Killed me!!!\n");
    exit(0);
}


/*
 * OUTPUT
 *

 [sgupta@rhel55x86 signal]$ gcc signal-1.c -o signal-1
 [sgupta@rhel55x86 signal]$ ./signal-1
 PARENT: sending SIGHUP
 CHILD: I have received a SIGHUP
 PARENT: sending SIGINT
 CHILD: I have received a SIGINT
 PARENT: sending SIGQUIT
 My DADDY has Killed me!!!
 [sgupta@rhel55x86 signal]$

*/

No comments:

Post a Comment