關於限制程式執行時間


Recommended Posts

目前我手上有一個c++程序,但這個程序在一般的狀況下需要等到使用者輸入回車號(enter)才會繼續執行下一個程序,例如cin、grtch();我希望限制程序執行的時間,例如說經過一秒後,使用者沒有做出輸入動做的話,便會強制結束本程序而執行下一個程序,請問該如何??

(我是用Dev-c++)

*2011.8.1修改*現在用code::blocks

此內容已被編輯, ,由 aalexx
鏈接文章
分享到其他網站

非同步IO

http://en.wikipedia.org/wiki/Asynchronous_I/O

1. 開子程式來解

在Linux的解法是用fork出來parent和child,

然後child等待輸入,parent計時,超過時間就把child終止,

windows上要用thread或是process解

對了,child如果抓到輸入的資料要傳回去給parent要嘛就要實做share memory

不然就要自己開socket作內部通訊

找到的python程式(第一個回覆的第一篇程式)

http://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-input


import thread
import threading

def raw_input_with_timeout(prompt, timeout=30.0):
print prompt,
timer = threading.Timer(timeout, thread.interrupt_main)
astring = None
try:
timer.start()
astring = raw_input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return astring

2. 用non blocking的輸入來作

linux上面有select和read可以用

http://www.unix.com/programming/16678-how-get-timed-input-using-cin.html


#include <sys/time.h>

int main()
{
fd_set fdset;
struct timeval timeout;
int rc;
int val;

timeout.tv_sec = 6; /* wait for 6 seconds for data */
timeout.tv_usec = 0;


FD_ZERO(&fdset);

FD_SET(0, &fdset);

rc = select(1, &fdset, NULL, NULL, &timeout);
if (rc == -1) /* select failed */
{
printf("ERROR path\n");
val='E';
}
else if (rc == 0) /* select timed out */
{
printf("DEFAULT path\n");
val='D';
}
else
{
if (FD_ISSET(0, &fdset))
{
val = getchar();
}
}
printf("VAL is %c\n", val);
}

鏈接文章
分享到其他網站

啦~~~~~~~看不懂~~~~~

不過還是謝謝

網路上查到同步執行(多緒執行)的都是Visual-c++或C++Builder

貌似Dev-c++不能多緒執行?

還請各位大大解答~~

(手上雖然有Visual-C++但是覺得很麻煩懶的學...)

鏈接文章
分享到其他網站

請登入後來留意見

在登入之後,您才能留意見



立即登入