Term :: ReadKey,原始模式下的非阻塞读取:检测EOF?

时间:2013-04-20 07:29:47

标签: perl unix io terminal stdio

当我将东西输入我的程序时,似乎没有像0x4这样的任何字符来表示EOF。

$ echo "abc" | map 'cat'
saw a: \x61
saw b: \x62
saw c: \x63
saw
: \x0A
zzzbc
^C

我必须按Ctrl + C退出,但我不确定Ctrl + C是在做什么。它可能让shell向管道发送SIGINT?我不知道管道如何在该级别上工作。

这是我的计划map

#!/usr/bin/env perl

use strict;
use warnings;

use IO::Pty::Easy;
use Term::ReadKey;
use Encode;

$#ARGV % 2 and die "Odd number of args required.\n";

if ($#ARGV == -1) {
    warn ("No args provided. A command must be specified.\n");
    exit 1;
}

# be sure to enter the command as a string
my %mapping = @ARGV[-@ARGV..-2];

my $interactive = -t STDIN;

# my %mapping = @ARGV;
# my @mapkeys = keys %mapping;

# warn @mapkeys;
if ($interactive) {
    print "Spawning command in pty: @ARGV\n"
    # print "\nContinue? (y/n)";
    # my $y_n;
    # while (($y_n = <STDIN>) !~ /^(y|n)$/) {
    #     print '(y/n)';
    # }
    # exit if $y_n eq "n\n";
}

my $pty = IO::Pty::Easy->new();
my $spawnret = $pty->spawn("@ARGV")."\n";

print STDERR "Spawning has failed: @ARGV\n" if !$spawnret;

ReadMode 4;
END {
    ReadMode 0; # Reset tty mode before exiting
}

my $i = undef;
my $j = 0;

{
    local $| = 1;
    while (1) {
        myread();

        # responsive to key input, and pty output may be behind by 50ms
        my $key = ReadKey(0.05);
        # last if !defined($key) || !$key;
        if (defined($key)) {
            my $code = ord($key); # this byte is...
            if ($interactive and $code == 4) {
                # User types Ctrl+D
                print STDERR "Saw ^D from term, embarking on filicide with TERM signal\n";
                $pty->kill("TERM", 0); # blocks till death of child
                myread();
                $pty->close();
                last;
            }
            printf("saw %s: \\x%02X\n", $key, $code);

            # echo translated input to pty
            if ($key eq "a") {
                $pty->write("zzz"); # print 'Saw "a", wrote "zzz" to pty';
            } else {
                $pty->write($key); # print "Wrote to pty: $key";
            }
        }
    }
}

sub myread {
    # read out pty's activity to echo to stdout
    my $from_pty = $pty->read(0);
    if (defined($from_pty)) {
        if ($from_pty) {
            # print "read from pty -->$from_pty<--\n";
            print $from_pty;
        } else {
            if ($from_pty eq '') {
                # empty means EOF means pty has exited, so I exit because my fate is sealed
                print STDERR "Got back from pty EOF, quitting\n" if $interactive;
                $pty->close();
                last;
            }
        }
    }
}

这可以解释为什么它会产生“zzzbc”。

现在我的问题是如何让map能够了解echo "abc"已达到输入结束?比照echo "abc" | cat自行完成。 ReadKey似乎没有提供用于确定这种情况的API。

同样地,我不知道如何做同样的事情将EOF传递给pty中的孩子。我认为当命令要写入文件或其他东西时,这可能会导致问题,因为EOF vs发送一个kill信号是正确写入文件而不是干净地退出之间的区别。

1 个答案:

答案 0 :(得分:0)

尝试从STDIN读取而不是那个$ pty对象。您通过shell创建的管道将数据传递给您的STDIN文件描述符0,其中perl是您的句柄。

$ pty,我认为这是你的终端。这就是脚本挂起的原因(我猜)。