windows下的C语言编程,需要对一段第三方dll中的函数进行超时控制,参考了很多种技术都没实现,请问该如何解决。
先说说我想到的东西:
1.中的alarm,这玩意儿在Linux下有效,在Windows中无法使用,即使我用的MinGW标准gcc编译器。
2.中的timeSetEvent,配合中的setjmp和longjmp,这个是最接近的,可惜运行到超时时中断是中断了,可是一直会弹窗报错,不知道为什么。
我在下面的评论中把第二个思路的代码贴出来,再截一个弹窗报警的图。
请教C语言和Win32API高手帮忙看看。
作者:丁丁
链接:https://www.zhihu.com/question/49052307/answer/113997254
来源:知乎
著作权归作者所有,转载请联系作者获得授权。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <setjmp.h>
jmp_buf j;
/**
* 时间中断函数
*/
void PASCAL OneMilliSecondProc(UINT wTimerID, UINT msg, DWORD dwUser, DWORD dwl, DWORD dw2) {
printf("Timout!\n");
longjmp(j,1);
}
int longTimeFunction(){
while (1) {
printf("operating...\n");
Sleep(1000);
}
return 0;
}
int main(){
HANDLE hHandle;
UINT wTimerRes_1ms;//定义时间间隔
UINT wAccuracy; //定义分辨率
UINT TimerID_1ms; //定义定时器句柄
wTimerRes_1ms = 5000;
if((TimerID_1ms = timeSetEvent(
wTimerRes_1ms,
wAccuracy,
(LPTIMECALLBACK)OneMilliSecondProc, // 回调函数
(DWORD)(1), // 用户传送到回调函数的数据;
TIME_PERIODIC//周期调用定时处理函数
)) == 0) {
printf("start!!!!!!!!!!!\n");
} else {
printf("end!!!!!!!!!!!\n");
}
int temp = 0;
if(setjmp(j) == 0){
temp = longTimeFunction();
}else{
printf("xxxxxx...\n");
temp = -1;
}
printf("%d\n", temp);
return 0;
}