当我将东西输入我的程序时,它似乎没有像 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 与发送终止信号是正确写入文件与不干净退出之间的区别。