超时功能

时间:2011-08-29 05:55:19

标签: c linux

我想制作一个代码,其中会要求用户名输入,但时间限制为15秒。如果用户越过限制&无法输入名称(或任何字符串),然后代码将被终止& “超时”按摩将显示,否则名称应保存& “谢谢”按摩将显示。我试过这样但是这是错的&不工作请给我一个解决方案..谢谢。

#include <stdio.h>
#include <time.h>

int timeout ( int seconds )
{
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}

    return  1;
}

int main ()
{
    char name[20];
    printf("Enter Username: (in 15 seconds)\n");
    printf("Time start now!!!\n");

    scanf("%s",name);
    if( timeout(5) == 1 ){
        printf("Time Out\n");
        return 0;
    }

    printf("Thnaks\n");
    return 0;
}

3 个答案:

答案 0 :(得分:12)

这个虚拟程序可能对你有所帮助:

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>

#define WAIT 3

int main ()
{
    char            name[20] = {0}; // in case of single character input
    fd_set          input_set;
    struct timeval  timeout;
    int             ready_for_reading = 0;
    int             read_bytes = 0;

    /* Empty the FD Set */
    FD_ZERO(&input_set );
    /* Listen to the input descriptor */
    FD_SET(0, &input_set);

    /* Waiting for some seconds */
    timeout.tv_sec = WAIT;    // WAIT seconds
    timeout.tv_usec = 0;    // 0 milliseconds

    /* Invitation for the user to write something */
    printf("Enter Username: (in %d seconds)\n", WAIT);
    printf("Time start now!!!\n");

    /* Listening for input stream for any activity */
    ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);
    /* Here, first parameter is number of FDs in the set, 
     * second is our FD set for reading,
     * third is the FD set in which any write activity needs to updated,
     * which is not required in this case. 
     * Fourth is timeout
     */

    if (ready_for_reading == -1) {
        /* Some error has occured in input */
        printf("Unable to read your input\n");
        return -1;
    } 

    if (ready_for_reading) {
        read_bytes = read(0, name, 19);
        if(name[read_bytes-1]=='\n'){
        --read_bytes;
        name[read_bytes]='\0';
        }
        if(read_bytes==0){
            printf("You just hit enter\n");
        } else {
            printf("Read, %d bytes from input : %s \n", read_bytes, name);
        }
    } else {
        printf(" %d Seconds are over - no data input \n", WAIT);
    }

    return 0;
}

<强>更新:
现在这是经过测试的代码。

另外,我已经从select的人那里得到了提示。本手册已经包含一个代码片段,用于从终端读取,并在没有活动的情况下在5秒内超时。

只是一个简短的解释,以防代码写得不够:

  1. 我们将输入流(fd = 1)添加到FD集。
  2. 我们发起select调用来收听为此创建的FD集 任何活动。
  3. 如果在timeout期内发生任何活动,那就是 通读read电话。
  4. 如果没有活动,则发生超时。
  5. 希望这有帮助。

答案 1 :(得分:4)

scanf()不是在有限的时间范围内获得输入的最佳功能。

相反,我会围绕select()(用于管理超时)和read()(用于获取输入)系统调用构建特定的输入函数。

答案 2 :(得分:1)

您必须考虑的一件事是,您的程序中只有一个执行线程。因此,仅在timeout函数终止时才会调用scanf函数。这不是你想要的。

执行此任务的一种方法是使用select函数。对于某些文件描述符(stdin)的输入可用性,它等待可能有限的时间(超时)。