-1

I have created an application that uses shared memory and child processes. When I want the program to close, I use my function 'controlledEnd' to kill any remaining child processes and destroy the shared memory but it seems that the code in the function does not get ran/does not complete and the print statements are never printed.

 /*
  controlledEnd

  This function safely exits the program ensuring there are no
  memory leaks and that the memory segment is freed.   

  The function takes 1 parameter
    -pid_t segmentID
        The segmentID of the shared memory
*/
void controlledEnd(pid_t segmentID){

    /*Kills all child processes*/
    if((int)kill(0, SIGKILL)==0){
        printf("All jobs successfully killed");
    }

    /*Logs an error if processes were not successfully killed*/
    else{
        logError("Any", "Could not kill processes on exit");
        perror("Could not deallocate memory on exit");
    }

    /*Frees the segment of shared memory used for the queue*/
    if((int)shmctl(segmentID, IPC_RMID, 0)==0){
        printf("Memory successfully deallocated");
    }

    /*Logs an error if the memory was not deallocated successfully*/
    else{
        logError("Either", "Could not deallocate memory on exit");
        perror("Could not deallocate memory on exit");
    }
    fflush(stdout);
    exit(0);
}

Any idea as to why my shared memory segment isn't being destroyed properly?

jww
  • 97,681
  • 90
  • 411
  • 885
  • Have you looked at what `kill(0, SIGKILL)` actually *does*? – EOF Jan 06 '19 at 20:14
  • I assume with 0 being passed as it's first parameter, SIGKILL is sent to every process in the process group – Ben Crossley Jan 06 '19 at 20:26
  • I've added an answer that spells it out but if you'd have thought about what EOF said you wouldn't have needed it. :-) – Jackson Jan 06 '19 at 20:40
  • Crucially, you can't even catch the `SIGKILL` in the `kill()`ing process. – EOF Jan 06 '19 at 20:45
  • You might also need to worry about zombies, see https://stackoverflow.com/questions/7171722/how-can-i-handle-sigchld/7171836#7171836 – Jackson Jan 06 '19 at 20:52

1 Answers1

0

Here's part of the man page for kill(3)

If pid is 0, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the process group ID of the sender, and for which the process has permission to send a signal.

So the process calling kill is part of the process group so it's killed along with all of the children and none of your tidyup code runs after that.

Jackson
  • 5,627
  • 2
  • 29
  • 48