问题描述
我正在尝试将 SIGINT (CNTRL C) 用于线程,但它有一个奇怪的行为。我正在尝试为线程创建者进程提供一个 SIGINT 函数,并为线程本身提供一个 SIGINT 函数。这是我试图实现的示例代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
pthread_t *cars;
void carEnd(){
printf("Car from team %ld killed.\n",(long)getpid());
pthread_exit(NULL);
}
void teamEnd(int signum){
for(int j=0; j<3; j++){
pthread_join(cars[j],NULL);
}
printf("Team %ld killed\n",(long)getpid());
exit(0);
}
void *carThread(void* team_number){
signal(SIGINT,carEnd);
sleep(10);
pthread_exit(NULL);
return NULL;
}
int main(){
signal(SIGINT,teamEnd);
int workerId[3];
pthread_t cars[3];
//Create the car threads
for(int i=0; i<3;i++){
workerId[i] = i+1;
pthread_create(&cars[i],NULL,carThread,&workerId[i]);
}
//Waits for all the cars to die
for(int j=0; 3; j++){
pthread_join(cars[j],NULL);
}
return 0;
}
`
执行后,如果没有检测到 SIGINT,程序将在 10 秒后关闭。如果检测到 SIGINT,则终端上会显示一条消息“来自团队的汽车......被杀”。如果有人能向我解释这种行为以及我如何解决它以实现我的目标,我将不胜感激!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)