【问题标题】:C program that waits for user input for a specific number of seconds [closed]等待用户输入特定秒数的C程序[关闭]
【发布时间】:2023-03-15 22:23:02
【问题描述】:

如何创建等待用户输入特定秒数的 C 程序?在时间限制之后,程序关闭,有或没有输入。请使用 fork() 和 sleep() 提供示例代码。抱歉,我是新手。

哇哦。对不起大家。这不是我的帖子。好像有人用了我的账号。而且我不能删除它。

【问题讨论】:

标签: c input fork sleep


【解决方案1】:

如果您只想让程序坐下来等待... 循环检查输入,请使用将时钟的开始时间保存在变量中。更新结束时间。如果时间(此处为 5 秒)已过期,请检查循环。

begin_t = clock();

// do-loop

   /* read user input*/
   end_t = clock();
// while( end_t - begin_t < 5 * CLOCKS_PER_SEC ) 

【讨论】:

    【解决方案2】:

    在我看来,使用 fork() 和 sleep() 并不是实现这种结果的最佳方式。最好使用 select() 调用,它允许超时等待数据。

    有关示例代码,请参阅 the unix manual page on select()

    【讨论】:

      【解决方案3】:

      执行此操作的正确方法是选择 STDIN 进行读取,并将超时设置为您想要的多长时间。 Select 将返回 STDIN 以供读取或不返回任何内容,这表示超时。

      http://linux.die.net/man/2/select

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 2022-12-13
        • 1970-01-01
        • 2011-08-27
        • 2023-03-14
        • 2014-07-03
        • 2012-05-21
        相关资源
        最近更新 更多