Home > database >  SHMDT and SHMCTL not deleting Shared Memory Location
SHMDT and SHMCTL not deleting Shared Memory Location

Time:02-22

I am currently practicing using fork to write some lines to shared memory and terminate once all lines printed. From my understanding after the program terminates shmdt and shmctl delete the shared memory location once executed. I have both of these statements and after my program ends I still see the shared memory location from running the program. For clarification I run in the terminal killall -u and then ipcrm --all to make sure I have no shared memory locations at run time. And after I run the there should be no memory locations.

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int
main()
{
    int           pid;
    int             segment_id;
    char           *shared_memory="User";
    const int       segment_size = 4096;
    segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR);
    shared_memory = (char *) shmat(segment_id, NULL, 0);
    
    sprintf(shared_memory, "I am process A");
    printf("%s\n", shared_memory);

    
    if (fork() == 0) { 
        sprintf(shared_memory, "I am process B");
        printf("%s\n", shared_memory);
        pause();
        exit(0);
    } else {
        if (fork() == 0){
            sprintf(shared_memory, "I am process C");
            printf("%s\n", shared_memory);
            pause();
            exit(0);
        }else{
            usleep(100);
            exit(0);
        }
        
    }
    if (shmdt(shared_memory) == -1) {
            fprintf(stderr, "Unable to detach\n");
        }
    shmctl(segment_id, IPC_RMID, NULL);
    return 0;
}

CodePudding user response:

TL;DR: send a signal to your child processes, and remove the exit(0) after your usleep(100)

Your parent process creates the segment, then forks. The forked process calls pause() which waits for a signal - none appear to be forthcoming.

The final branch of the if/else/[if/else] sleeps and then exits, so your attempt to shmdt() is never executed.

  • Related