firstlegagain1
firstlegagain1

Reputation: 127

How to send a signal from the child process to parent process through kill command

I am trying to create a child process through fork() system call, then trying to send a signal to parent and print out something on the screen.

Here is my code:-

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

void func1(int signum) {
    if(signum == SIGUSR2) {
        printf("Received sig from child\n");
    }
}

int main() {
    signal(SIGUSR2, func1);

    int c = fork();
    if(c > 0) {
        printf("parent\n");
    }
    else if(c == -1) {
        printf("No child");
    }
    else {
        kill(getppid(), SIGUSR2);
        printf("child\n");
    }

}

When I execute my program all I get is:-

child
Segmentation fault (core dumped)

I am a novice to C language system calls, and don't get why this is happening, and how to get the desired output, which would be printing of all the three printf statements. Any help for the same would be appreciated.

Upvotes: 0

Views: 2690

Answers (1)

P.P
P.P

Reputation: 121427

Your code has a number of minor issues and certainly has undefined behaviour i.e., you can't call printf or other async-signal unsafe functions from a signal handler. This is the code with fixes (see comments in code). This should work as expected (with no particular order of print statements) and see if still get a segfault with this code.

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

void func1(int signum)
{
    /* write is asyc-signal-safe */
    write(1, "Received sig from child\n", sizeof "Received sig from child\n" - 1);
}

int main()
{
    signal(SIGUSR2, func1);

    /* fork returns a pid_t */
    pid_t c = fork();
    if(c > 0) {
        printf("parent\n");
        /* Wait for the child to exit; otherwise, you may not receive the signal */
        if (wait(NULL) == -1) {
            printf("wait(2) failed\n");
            exit(1);
        }
    } else if (c == -1) {
        printf("fork(2) error\n");
        exit(1);
    } else {
        if (kill(getppid(), SIGUSR2) == -1) {
            /* In case kill fails to send signal... */
            printf("kill(2) failed\n");
            exit(1);
        }
        printf("child\n");
    }
}

Upvotes: 3

Related Questions