⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlfaq8.pod

📁 MSYS在windows下模拟了一个类unix的终端
💻 POD
📖 第 1 页 / 共 3 页
字号:
=head1 NAMEperlfaq8 - System Interaction ($Revision: 1.39 $, $Date: 1999/05/23 18:37:57 $)=head1 DESCRIPTIONThis section of the Perl FAQ covers questions involving operatingsystem interaction.  Topics include interprocess communication (IPC),control over the user-interface (keyboard, screen and pointingdevices), and most anything else not related to data manipulation.Read the FAQs and documentation specific to the port of perl to youroperating system (eg, L<perlvms>, L<perlplan9>, ...).  These shouldcontain more detailed information on the vagaries of your perl.=head2 How do I find out which operating system I'm running under?The $^O variable ($OSNAME if you use English) contains an indication ofthe name of the operating system (not its release number) that your perlbinary was built for.=head2 How come exec() doesn't return?Because that's what it does: it replaces your currently runningprogram with a different one.  If you want to keep going (as isprobably the case if you're asking this question) use system()instead.=head2 How do I do fancy stuff with the keyboard/screen/mouse?How you access/control keyboards, screens, and pointing devices("mice") is system-dependent.  Try the following modules:=over 4=item Keyboard    Term::Cap			Standard perl distribution    Term::ReadKey		CPAN    Term::ReadLine::Gnu		CPAN    Term::ReadLine::Perl	CPAN    Term::Screen		CPAN=item Screen    Term::Cap			Standard perl distribution    Curses			CPAN    Term::ANSIColor		CPAN=item Mouse    Tk				CPAN=backSome of these specific cases are shown below.=head2 How do I print something out in color?In general, you don't, because you don't know whetherthe recipient has a color-aware display device.  If youknow that they have an ANSI terminal that understandscolor, you can use the Term::ANSIColor module from CPAN:    use Term::ANSIColor;    print color("red"), "Stop!\n", color("reset");    print color("green"), "Go!\n", color("reset");Or like this:    use Term::ANSIColor qw(:constants);    print RED, "Stop!\n", RESET;    print GREEN, "Go!\n", RESET;=head2 How do I read just one key without waiting for a return key?Controlling input buffering is a remarkably system-dependent matter.On many systems, you can just use the B<stty> command as shown inL<perlfunc/getc>, but as you see, that's already getting you intoportability snags.      open(TTY, "+</dev/tty") or die "no tty: $!";    system "stty  cbreak </dev/tty >/dev/tty 2>&1";    $key = getc(TTY);		# perhaps this works    # OR ELSE    sysread(TTY, $key, 1);	# probably this does    system "stty -cbreak </dev/tty >/dev/tty 2>&1";The Term::ReadKey module from CPAN offers an easy-to-use interface thatshould be more efficient than shelling out to B<stty> for each key.It even includes limited support for Windows.    use Term::ReadKey;    ReadMode('cbreak');    $key = ReadKey(0);    ReadMode('normal');However, using the code requires that you have a working C compilerand can use it to build and install a CPAN module.  Here's a solutionusing the standard POSIX module, which is already on your systems(assuming your system supports POSIX).    use HotKey;    $key = readkey();And here's the HotKey module, which hides the somewhat mystifying callsto manipulate the POSIX termios structures.    # HotKey.pm    package HotKey;    @ISA = qw(Exporter);    @EXPORT = qw(cbreak cooked readkey);    use strict;    use POSIX qw(:termios_h);    my ($term, $oterm, $echo, $noecho, $fd_stdin);    $fd_stdin = fileno(STDIN);    $term     = POSIX::Termios->new();    $term->getattr($fd_stdin);    $oterm     = $term->getlflag();    $echo     = ECHO | ECHOK | ICANON;    $noecho   = $oterm & ~$echo;    sub cbreak {        $term->setlflag($noecho);  # ok, so i don't want echo either        $term->setcc(VTIME, 1);        $term->setattr($fd_stdin, TCSANOW);    }    sub cooked {        $term->setlflag($oterm);        $term->setcc(VTIME, 0);        $term->setattr($fd_stdin, TCSANOW);    }    sub readkey {        my $key = '';        cbreak();        sysread(STDIN, $key, 1);        cooked();        return $key;    }    END { cooked() }    1;=head2 How do I check whether input is ready on the keyboard?The easiest way to do this is to read a key in nonblocking mode with theTerm::ReadKey module from CPAN, passing it an argument of -1 to indicatenot to block:    use Term::ReadKey;    ReadMode('cbreak');    if (defined ($char = ReadKey(-1)) ) {        # input was waiting and it was $char    } else {        # no input was waiting    }    ReadMode('normal');                  # restore normal tty settings=head2 How do I clear the screen?If you only have do so infrequently, use C<system>:    system("clear");If you have to do this a lot, save the clear stringso you can print it 100 times without calling a program100 times:    $clear_string = `clear`;    print $clear_string;If you're planning on doing other screen manipulations, like cursorpositions, etc, you might wish to use Term::Cap module:    use Term::Cap;    $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );    $clear_string = $terminal->Tputs('cl');=head2 How do I get the screen size?If you have Term::ReadKey module installed from CPAN, you can use it to fetch the width and height in charactersand in pixels:    use Term::ReadKey;    ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();This is more portable than the raw C<ioctl>, but not as illustrative:    require 'sys/ioctl.ph';    die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;    open(TTY, "+</dev/tty")                     or die "No tty: $!";    unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {        die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;    }    ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);    print "(row,col) = ($row,$col)";    print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;    print "\n";=head2 How do I ask the user for a password?(This question has nothing to do with the web.  See a differentFAQ for that.)There's an example of this in L<perlfunc/crypt>).  First, you put theterminal into "no echo" mode, then just read the password normally.You may do this with an old-style ioctl() function, POSIX terminalcontrol (see L<POSIX> or its documentation the Camel Book), or a callto the B<stty> program, with varying degrees of portability.You can also do this for most systems using the Term::ReadKey modulefrom CPAN, which is easier to use and in theory more portable.    use Term::ReadKey;    ReadMode('noecho');    $password = ReadLine(0);=head2 How do I read and write the serial port?This depends on which operating system your program is running on.  Inthe case of Unix, the serial ports will be accessible through files in/dev; on other systems, device names will doubtless differ.Several problem areas common to all device interaction are thefollowing:=over 4=item lockfilesYour system may use lockfiles to control multiple access.  Make sureyou follow the correct protocol.  Unpredictable behavior can resultfrom multiple processes reading from one device.=item open modeIf you expect to use both read and write operations on the device,you'll have to open it for update (see L<perlfunc/"open"> fordetails).  You may wish to open it without running the risk ofblocking by using sysopen() and C<O_RDWR|O_NDELAY|O_NOCTTY> from theFcntl module (part of the standard perl distribution).  SeeL<perlfunc/"sysopen"> for more on this approach.=item end of lineSome devices will be expecting a "\r" at the end of each line ratherthan a "\n".  In some ports of perl, "\r" and "\n" are different fromtheir usual (Unix) ASCII values of "\012" and "\015".  You may have togive the numeric values you want directly, using octal ("\015"), hex("0x0D"), or as a control-character specification ("\cM").    print DEV "atv1\012";	# wrong, for some devices    print DEV "atv1\015";	# right, for some devicesEven though with normal text files a "\n" will do the trick, there isstill no unified scheme for terminating a line that is portablebetween Unix, DOS/Win, and Macintosh, except to terminate I<ALL> lineends with "\015\012", and strip what you don't need from the output.This applies especially to socket I/O and autoflushing, discussednext.=item flushing outputIf you expect characters to get to your device when you print() them,you'll want to autoflush that filehandle.  You can use select()and the C<$|> variable to control autoflushing (see L<perlvar/$|>and L<perlfunc/select>, or L<perlfaq5>, ``How do I flush/unbuffer anoutput filehandle?  Why must I do this?''):    $oldh = select(DEV);    $| = 1;    select($oldh);You'll also see code that does this without a temporary variable, as in    select((select(DEV), $| = 1)[0]);Or if you don't mind pulling in a few thousand linesof code just because you're afraid of a little $| variable:    use IO::Handle;    DEV->autoflush(1);As mentioned in the previous item, this still doesn't work when usingsocket I/O between Unix and Macintosh.  You'll need to hardcode yourline terminators, in that case.=item non-blocking inputIf you are doing a blocking read() or sysread(), you'll have toarrange for an alarm handler to provide a timeout (seeL<perlfunc/alarm>).  If you have a non-blocking open, you'll likelyhave a non-blocking read, which means you may have to use a 4-argselect() to determine whether I/O is ready on that device (seeL<perlfunc/"select">.=backWhile trying to read from his caller-id box, the notorious Jamie Zawinski<jwz@netscape.com>, after much gnashing of teeth and fighting with sysread,sysopen, POSIX's tcgetattr business, and various other functions thatgo bump in the night, finally came up with this:    sub open_modem {	use IPC::Open2;	my $stty = `/bin/stty -g`;	open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");	# starting cu hoses /dev/tty's stty settings, even when it has	# been opened on a pipe...	system("/bin/stty $stty");	$_ = <MODEM_IN>;	chomp;	if ( !m/^Connected/ ) {	    print STDERR "$0: cu printed `$_' instead of `Connected'\n";	}    }=head2 How do I decode encrypted password files?You spend lots and lots of money on dedicated hardware, but this isbound to get you talked about.Seriously, you can't if they are Unix password files--the Unixpassword system employs one-way encryption.  It's more like hashing thanencryption.  The best you can check is whether something else hashes tothe same string.  You can't turn a hash back into the original string.Programs like Crackcan forcibly (and intelligently) try to guess passwords, but don't(can't) guarantee quick success.If you're worried about users selecting bad passwords, you shouldproactively check when they try to change their password (by modifyingpasswd(1), for example).=head2 How do I start a process in the background?You could use    system("cmd &")or you could use fork as documented in L<perlfunc/"fork">, withfurther examples in L<perlipc>.  Some things to be aware of, if you'reon a Unix-like system:=over 4=item STDIN, STDOUT, and STDERR are sharedBoth the main process and the backgrounded one (the "child" process)share the same STDIN, STDOUT and STDERR filehandles.  If both try toaccess them at once, strange things can happen.  You may want to closeor reopen these for the child.  You can get around this withC<open>ing a pipe (see L<perlfunc/"open">) but on some systems thismeans that the child process cannot outlive the parent.=item Signals

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -