简体   繁体   中英

Ending terminal application on mac + cleanup process

I am trying to create ac program which has an infinite loop in the main method (multi-threaded application). We are using pthreads and POSIX shared memory between two applications. If I exit one of the programs using the command line (CTL+C), then I want to run a cleanup method to cleanup all allocated memory and removed the POSIX shared memory map.

int main () {
    for (;;)
    {
    }
    
        destroy_shared_object(shm, MEM_MAP_SIZE);
        exit(EXIT_SUCCESS);
        return 0;
}

Right now this is what I have above, however when I exit the program I don't think it removes the shared memory map and cleans up. Any help would be appreciated!

You may catch CTRL+C with a signal() handler and set a flag variable within the signal handler:

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

static volatile sig_atomic_t running = 1;

void sighandler(int signum) {
   running = 0;
}

int main() {
   signal(SIGINT, sighandler);

   while(running) {
      sleep(1); 
   }

   printf("Do the cleanup...\n");

   return 0;
}

EDIT:

It's probably better to use sigaction() instead:

 WARNING: the behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead. See > Portability below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM