【问题标题】:Getting user input as the program loop still runs在程序循环仍在运行时获取用户输入
【发布时间】:2016-01-20 15:11:42
【问题描述】:

我的脚本基本上是这样的:

sub mainLoop {
    while (1) {
        # Do its thing
    }
}

我认为逻辑根本不重要,它基本上是不断检查服务器并在必要时执行一些操作。但我想确保用户可以在程序运行时输入一些命令,例如show statusshow foo。并打印一些东西,比如它必须采取行动的次数等。总而言之,它需要在不暂停循环的情况下从 STDIN 读取。

我阅读了另一个执行此操作的 Perl 程序的源代码。但我不确定我是否得到它:

sub mainLoop {
    while (1) {
        # This is just for the sake of of this example
        my $bits = '';
        my $line = undef;

        vec($bits, fileno(STDIN), 1) = 1;

        if (select($bits, undef, undef, 0) > 0) {
            $line = <STDIN>;
            $line =~ s/\n//g;
        }

        if ($line) {
            # I can work with $line value and call a sub based on its value 
        }
        # Keep on doing its thing
    }
}

我没有收到select()。它如何变为大于 0 的值?因为据我所知,$bits 的值与 select() 的值是否等于 0 或大于 0 相同。那么为什么当我按下 ENTER 键时 select 返回的值会变为 1 ?

【问题讨论】:

  • 我建议您改用IO::Select 模块,它将select 调用包装在一个更整洁的API 中

标签: perl


【解决方案1】:

select 返回最高文件描述符+1,以防某些文件描述符被通知。因此,如果STDIN 上没有任何内容,它将为0,如果有一些字节等待读取,则为1(注意STDIN 是fd 0 所以0+1 是1 - 返回值)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多