如何在一段时间后停用输入语句? [英] How to deactivate input statement after some time?

查看:138
本文介绍了如何在一段时间后停用输入语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道输入功能或操作(CIN,scanf函数,得到... .etc)迫不及待地采取输入表单用户放大器;这时候已经没有任何限制。

We know input function or operator (cin, scanf,gets….etc) wait to take input form user & this time has no limit.

现在,我会问一个问题:放大器;用户给出答案,到现在为止有没有问题,但我的问题是用户有一个时间(5月30日或40秒),为输入,如果他失败,则输入语句将自动关闭和放大器;执行下一条语句。

Now, I will ask a question & user give the answer, till now there no problem but my problem is "user has a time(may 30 or 40 sec) to give the input, if he fail then input statement will automatically deactivated & execute next statement."

我想你明白我的问题。然后,请帮我在这种情况下。这将是更好的,如果有人给我一些真正的工作例如code。

I think you get my problem. Then please help me in this situation. It will be better if someone give me some really working example code.

我用$ C $ 12.11 cbolck在Windows 7中。

I use codebolck 12.11 in windows 7.

推荐答案

有关* IX'ish系统(包括Cygwin的Windows上)的一种方法:

An approach for *IX'ish systems (including Cygwin on windows):

您可以使用报警()来安排 SIGALRM ,然后用阅读(的fileno(标准输入),...)

You could use alarm() to schedule a SIGALRM, then use read(fileno(stdin), ...).

在信号到达阅读() 1 返回并已成立错误号 EINTR

When the signal arrives read() shall return with -1 and had set errno to EINTR.

例如:

#define _POSIX_SOURCE 1

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

void handler_SIGALRM(int signo)
{
  signo = 0; /* Get rid of warning "unused parameter ‘signo’" (in a portable way). */

  /* Do nothing. */
}

int main()
{
  /* Override SIGALRM's default handler, as the default handler might end the program. */
  {
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));

    sa.sa_handler = handler_SIGALRM;

    if (-1 == sigaction(SIGALRM, &sa, NULL ))
    {
      perror("sigaction() failed");
      exit(EXIT_FAILURE);
    }
  }

  alarm(2); /* Set alarm to occur in two seconds. */

  {
    char buffer[16] = { 0 };

    int result = read(fileno(stdin), buffer, sizeof(buffer) - 1);
    if (-1 == result)
    {
      if (EINTR != errno)
      {
        perror("read() failed");
        exit(EXIT_FAILURE);
      }

      printf("Game over!\n");
    }
    else
    {
      alarm(0); /* Switch of alarm. */

      printf("You entered '%s'\n", buffer);
    }
  }

  return EXIT_SUCCESS;
}

请注意:在阻塞调用到上面的例子阅读()将在任何信号到达interupted。在code,以避免这个就留给execise读者...: - )

Note: In the example above the blocking call to read() would be interupted on any signal arriving. The code to avoid this is left as an execise to the reader ... :-)

这篇关于如何在一段时间后停用输入语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆