Clear dynamically allocated data with a signal

What is the correct way to clear with free()dynamically allocated data in C when using a signal?

There is an example with shared memory, and the solution used is to declare a global variable, but it seems not very clean and safe.

This is sample code with an array of dynamically distributed structure that is not properly cleaned.

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

typedef struct {
    int val;
} mystruct_t;

void sigquit(int sig) {
    signal(sig, SIG_IGN);
    printf("Child killed\n");

    // Clear the dynamic allocated data inside
    // the signal quit method
    //
    // int i;
    // for (i = 0; i < n; i++) {
    //     free(struct_a[i]);
    // }
    // free(struct_a);

    exit(0);
}

int
main()
{
    int n = 10;
    /* dynamic allocated array of structure */
    mystruct_t **struct_a = generatearray(n);
    pid_t pid = fork();

    if (pid == 0) {
        printf("Child process. My pid is %d and my parent id is %d.\n",
            getpid(), getppid());

        if (signal(SIGQUIT, sigquit) == SIG_ERR) {
            printf("SIGINT install error\n");
            exit(1);
        }

        while(1);
    }
    else {
        printf("Parent process. My pid is %d and my parent id is %d.\n",
            getpid(), pid);

        sleep(1);
        kill(pid, SIGQUIT);
        sleep(5);
    }

    return 0;
}

What method would you use to solve this problem?

+4
source share
3 answers

POSIX malloc(), free(), - (mmap() ). , , .

, . . sig_atomic_t volatile .

+4

sig_atomic_t. , , , , . , , . "".

+2

(, malloced memory) . , .

, , , SIGQUIT, .

0

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


All Articles