[英]Wait termination of threads work before close a server after receiving SIGINT or SIGTERM (Posix thread in C)
I'm developing a client / server in C using pthread. 我正在使用pthread在C中开发客户端/服务器。
It's a card game where server
is the dealer between two clients
that play. 这是一种纸牌游戏,其中
server
是两个玩游戏的clients
之间的发行商。
I have this situation 我有这种情况
server.c : server.c :
main: 主要:
int main (int argc, char * argv[])
using as a thread dispatcher for listening eventually entering connection on accept
用作线程调度程序,用于侦听最终在
accept
进入连接
pthread_create(&sig_thread, NULL, &thread_signal_handler, &server_Socket );
thread to catch signals (maskered conveniently) created inside main function 捕获主函数内部创建的信号(方便地进行屏蔽)的线程
pthread_create(&tid[i++], NULL, &worker, (void*) arr_args)
every client is associated to a thread created ( tid is the array of thread ID) 每个客户端都与创建的线程相关联( tid是线程 ID的数组)
pthread_join(sig_thread, NULL)
to join thread for signals 加入信号线程
pthread_join(tid[i], NULL)
to join thread created for every client connected. 加入为每个连接的客户端创建的线程。
worker: 工人:
void * worker(void * args)
do his job and terminated 做他的工作并终止
thread signal handler: 线程信号处理程序:
void * thread_signal_handler(void * arg)
void * thread_signal_handler(void * arg) {
无效* thread_signal_handler(无效* arg){
sigset_t set; int sig, n; int * socket = (int*) arg; sigemptyset(&set); sigaddset(&set, SIGINT); sigaddset(&set,SIGTERM); while (server_UP) { /* wait for a signal */ if (sigwait(&set, &sig)) perror("Sigwait"); /* received SIGINT or SIGTERM - closing server */ if ((sig == SIGINT || sig == SIGTERM)) { printf(TERM_SERVER"\\n"); server_UP = 0; /* global variable */ /* close socket blocked on MAIN */ shutdown( *socket, SHUT_RDWR ); } return (void *) EXIT_SUCCESS;
}
}
In this way, the signal is catched well and the server is terminated immediately. 这样,可以很好地捕获信号,并立即终止服务器。 I need, if there are matches in progress, to waiting that all the workers finish their jobs properly, so I want to know how to say to thread handler "did you receive a SIGINT (or SIGTERM)? Ok, waiting the termination of all workers".
我需要的,如果有正在进行的比赛,等待所有的工人正确完成自己的工作,所以我想知道怎么说线程处理器“你有没有收到一个SIGINT(或SIGTERM)?好吧,等待所有的终止工作人员”。
Any suggests? 有什么建议吗? If you need more code, i'll edit this post.
如果您需要更多代码,我将编辑这篇文章。
When you create them you can save all of the threads in an array or a list and at the end call pthread_join() on all of them. 创建它们时,可以将所有线程保存在数组或列表中,最后在所有线程上调用pthread_join()。
while (pthread_list) {
pthread_join(pthread_list->th_id, NULL);
pthread_list = pthread_list->next;
}
If you don't want to keep track of all threads you can keep a count of running threads, increment it before calling pthread_create, decrement the count as each thread finishes. 如果不想跟踪所有线程,则可以保留正在运行的线程数,请在调用pthread_create之前将其递增,并在每个线程完成时递减计数。
Then in the handler you'll sleep for some seconds iteratively until the count becomes 0. 然后在处理程序中,您将迭代睡眠几秒钟,直到计数变为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.