小编典典

超时功能

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;
}

阅读 373

收藏
2020-06-02

共1个答案

小编典典

该虚拟程序可能会帮助您:

#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;
}

更新:
这是经过测试的代码。

另外,我从man那里得到了一些提示select。本手册已包含一个代码段,该代码段可用于从终端读取内容,并且在无活动的情况下会在5秒内超时。

如果代码编写得不够好,请做一个简短的解释:

  1. 我们将输入流(fd = 1)添加到FD集。
  2. 我们发起select呼叫以侦听为任何活动创建的此FD集。
  3. 如果在此timeout期间内发生任何活动,则通过read调用读取该活动。
  4. 如果没有活动,则会发生超时。

希望这可以帮助。

2020-06-02