Ignoring SIGCHLD in some cases, but not for others

In my program, I fork () several times depending on user input.

In some cases, I want to process SIGCHLD and say something like "Process # Finished". In other cases, however, I want to ignore this signal.

How can i do this?

+3
source share
4 answers

Signal processing is configured globally for the process. If you want to catch an asynchronous signal, such as SIGCHLD, when some children complete but not others, you cannot ignore it in advance for some.

You will need to process the signal every time in the parent, and then decide whether you want to ignore it in your handler.

, wait() (si_pid siginfo_t), . , . , .

+4

SIGCHLD, . signal() (man signal). child_died() , SIGCHLD ( ). , , child_died() , (man pipe). :

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

#define MAX_SIZE 256

void child_died(int);

int fd[2];

int main()
{
    int pid;
    extern int fd[];
    char *str;

    pipe(fd);
    signal(SIGCHLD, child_died);

    if ((pid = fork()) < 0) {
        // error
        printf("Error\n");
    } else if (pid == 0) {
        // child
        printf("In child process\n");
        close(fd[0]);
        str = strdup("Message from child process.\n");
        write(fd[1], str, strlen(str) + 1);
    } else {
        // parent
        wait();
        printf("Now in parent\n");
    }

    return 0;
}

void child_died(int s)
{
    char *str;
    close(fd[1]);
    read(fd[0], str, MAX_SIZE);
    printf("%s", str);
}

sigchld.c : gcc -Wall sigchld.c -o sigchld

int (, pid) - , , .

SIGCHLD, child_died(). if. , , , , . , , child_died() , .

, . , . , .

+3

You can use the function waitpidin blocking or non-blocking mode to wait for a signal from a given child, and then perform some processing. In fact, you have to use waitsome type, as indicated in Graham's answer ...

+2
source

If you ignore SIGCHLD, then the process table will be filled with zombies.

0
source

Source: https://habr.com/ru/post/1704522/


All Articles