简体   繁体   中英

How to close all the threads before main thread by interrupting ctrl+c?

I have created pool of 5 threads using _beginthread() in C. All the threads from pool will run infinitely to do job received from client. For example, when client will be connected, the free thread from pool will handle this. After completing its task the thread will wait for next client. Now my problem is that, whenever I enter ctrl+c from server, the program get terminated. But I want to close all the running and waiting threads from pool before terminating the main thread.

For Windows

#include <windows.h> 
#include <stdio.h> 

BOOL WINAPI signal_handler(DWORD signal) {

    if (signal == CTRL_C_EVENT){
        printf("CTRL C caught here .\n");
    }
    return TRUE;
}

main()
{
    ....
    SetConsoleCtrlHandler(signal_handler, TRUE);

   .....

     printf("This should appear after signal_handler\n");
}

For linux

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

void signal_handler() 
{
    printf("CTRL C caught here .\n");
}

main() 
{

    ...
    // SIGINT is signal name create  when Ctrl+c will pressed 
    signal(SIGINT,signal_handler);  



    printf("This should appear after signal_handler\n");

}

Once ctrl-c is captured you can close all the threads and other cleanup stuff

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