0

I'm beginner to signal and practicing by writing a function kill_parent_process that will be used as a signal handler.

This func will asks parents to exit() (either sending SIGKILL or other methods). The way I did is let child sending a signal to parents and the handler exit(). But I do feel this is where the problem because when I exit, I might just exit in child process. However, it looks like the handler never been called. Here is my code

void kill_parent_process(int code) {
    fprintf(stderr, "KIll the Parent\n");
    exit(1);
}

int main() {
    struct sigaction sa;
    sa.sa_handler = kill_parent_process;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    int r = fork();

    if (r == 0) {


        sigaction(SIGUSR1, &sa, NULL);

        kill(getppid(), SIGUSR1);
        exit(1);
    } else if (r > 0) {

        while (1) {
            sleep(1);
            printf("%d\n",getpid());
        }
        int status;
        wait(&status);
        if (WIFEXITED(status)) {
            int result = WEXITSTATUS(status);
            fprintf(stderr, "%d\n", result);
        }

      } 
    }

I receive a message User defined signal 1: 30 when I ran the program and kill_parent_process never been called. What is the problem with this code?

ElleryL
  • 507
  • 7
  • 16

1 Answers1

0

the following proposed code:

  1. performs the desired functionality
  2. cleanly compiles
  3. documents why most of the header files are being included
  4. does not invoke any signal handlers, etc, rather uses the default action
  5. properly checks for and handles errors

and now the proposed code:

#include <stdio.h>   // perror(), puts()
#include <stdlib.h>  // exit(), EXIT_FAILURE, EXIT_SUCCESS
#include <sys/types.h>  // for 'kill()' and 'getppid()'
#include <signal.h>  // kill()
#include <unistd.h>  // getppid(), fork()

int main( void )
{
    pid_t pid = fork();

    if( pid < 0 )
    {
        perror( "fork failed" );
        exit( EXIT_FAILURE );
    }

    else if( pid == 0 )
    {  // then child
        puts( "in child process" );
        kill( getppid(), SIGUSR1 );
        exit( EXIT_SUCCESS );
    }

    else // if ( pid > 0 )
    { // then parent
        while(1)
        {
            puts( "in parent process" );
            sleep(1);
        }
    }
}

the (typical) output of the proposed code is:

in parent process
in child process
User defined signal 1
user3629249
  • 16,402
  • 1
  • 16
  • 17