简体   繁体   English

如何通过中断ctrl + c关闭主线程之前的所有线程?

[英]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. 我已经在C中使用_beginthread()创建了5个线程池。池中的所有线程将无限运行以完成从客户端接收的工作。 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. 现在我的问题是,每当我从服务器输入ctrl+c时,程序都会终止。 But I want to close all the running and waiting threads from pool before terminating the main thread. 但是我想在终止主线程之前从池中关闭所有正在运行和正在等待的线程。

For Windows 对于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 对于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 捕获ctrl-c之后,您可以关闭所有线程和其他清理内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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