Hi, I work on code something like this
... HEADERS ...
int *var;
void child() {
... //some work
free(var);
exit(EXIT_SUCCESSFUL);
}
int main(void) {
...
//allocate variable
var = (int *) malloc(N*sizeof(int));
... //work with var
for(int i; i<PROC_COUNT; i++) {
pid_t child = fork();
if(pid == 0) {
child(); //main function of new proces
break;
}
elseif(pid < 0) {
//there is enormous problem -> kill every proces
kill(0, SIGTERM);
waitpid(0, NULL, 0); //wait for children
free(var);
exit(EXIT_FAILURE);
}
}
free(var);
return EXIT_SUCCESS;
}
When process is forked, all variables are cloned too. In regular case all copies of var are freed.
If there is error by fork()
, I send signal SIGTERM to all created processes. And I need to write signal handler for SIGTERM which free var and terminate application. However, free() is not signal safe function
-- so I shouldn`t call it. But how to free() that variable?
A lot of thanks for your answers...
EDIT: valgrind also shows still reacheable variable:
==5928== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 1)
==5928== malloc/free: in use at exit: 20 bytes in 1 blocks.
==5928== malloc/free: 1 allocs, 0 frees, 20 bytes allocated.
==5928== For counts of detected errors, rerun with: -v
==5928== searching for pointers to 1 not-freed blocks.
==5928== checked 49,164 bytes.