1=head1 NAME 2 3perlfaq8 - System Interaction ($Revision: 1.17 $, $Date: 2003/01/26 17:44:04 $) 4 5=head1 DESCRIPTION 6 7This section of the Perl FAQ covers questions involving operating 8system interaction. Topics include interprocess communication (IPC), 9control over the user-interface (keyboard, screen and pointing 10devices), and most anything else not related to data manipulation. 11 12Read the FAQs and documentation specific to the port of perl to your 13operating system (eg, L<perlvms>, L<perlplan9>, ...). These should 14contain more detailed information on the vagaries of your perl. 15 16=head2 How do I find out which operating system I'm running under? 17 18The $^O variable ($OSNAME if you use English) contains an indication of 19the name of the operating system (not its release number) that your perl 20binary was built for. 21 22=head2 How come exec() doesn't return? 23 24Because that's what it does: it replaces your currently running 25program with a different one. If you want to keep going (as is 26probably the case if you're asking this question) use system() 27instead. 28 29=head2 How do I do fancy stuff with the keyboard/screen/mouse? 30 31How you access/control keyboards, screens, and pointing devices 32("mice") is system-dependent. Try the following modules: 33 34=over 4 35 36=item Keyboard 37 38 Term::Cap Standard perl distribution 39 Term::ReadKey CPAN 40 Term::ReadLine::Gnu CPAN 41 Term::ReadLine::Perl CPAN 42 Term::Screen CPAN 43 44=item Screen 45 46 Term::Cap Standard perl distribution 47 Curses CPAN 48 Term::ANSIColor CPAN 49 50=item Mouse 51 52 Tk CPAN 53 54=back 55 56Some of these specific cases are shown below. 57 58=head2 How do I print something out in color? 59 60In general, you don't, because you don't know whether 61the recipient has a color-aware display device. If you 62know that they have an ANSI terminal that understands 63color, you can use the Term::ANSIColor module from CPAN: 64 65 use Term::ANSIColor; 66 print color("red"), "Stop!\n", color("reset"); 67 print color("green"), "Go!\n", color("reset"); 68 69Or like this: 70 71 use Term::ANSIColor qw(:constants); 72 print RED, "Stop!\n", RESET; 73 print GREEN, "Go!\n", RESET; 74 75=head2 How do I read just one key without waiting for a return key? 76 77Controlling input buffering is a remarkably system-dependent matter. 78On many systems, you can just use the B<stty> command as shown in 79L<perlfunc/getc>, but as you see, that's already getting you into 80portability snags. 81 82 open(TTY, "+</dev/tty") or die "no tty: $!"; 83 system "stty cbreak </dev/tty >/dev/tty 2>&1"; 84 $key = getc(TTY); # perhaps this works 85 # OR ELSE 86 sysread(TTY, $key, 1); # probably this does 87 system "stty -cbreak </dev/tty >/dev/tty 2>&1"; 88 89The Term::ReadKey module from CPAN offers an easy-to-use interface that 90should be more efficient than shelling out to B<stty> for each key. 91It even includes limited support for Windows. 92 93 use Term::ReadKey; 94 ReadMode('cbreak'); 95 $key = ReadKey(0); 96 ReadMode('normal'); 97 98However, using the code requires that you have a working C compiler 99and can use it to build and install a CPAN module. Here's a solution 100using the standard POSIX module, which is already on your systems 101(assuming your system supports POSIX). 102 103 use HotKey; 104 $key = readkey(); 105 106And here's the HotKey module, which hides the somewhat mystifying calls 107to manipulate the POSIX termios structures. 108 109 # HotKey.pm 110 package HotKey; 111 112 @ISA = qw(Exporter); 113 @EXPORT = qw(cbreak cooked readkey); 114 115 use strict; 116 use POSIX qw(:termios_h); 117 my ($term, $oterm, $echo, $noecho, $fd_stdin); 118 119 $fd_stdin = fileno(STDIN); 120 $term = POSIX::Termios->new(); 121 $term->getattr($fd_stdin); 122 $oterm = $term->getlflag(); 123 124 $echo = ECHO | ECHOK | ICANON; 125 $noecho = $oterm & ~$echo; 126 127 sub cbreak { 128 $term->setlflag($noecho); # ok, so i don't want echo either 129 $term->setcc(VTIME, 1); 130 $term->setattr($fd_stdin, TCSANOW); 131 } 132 133 sub cooked { 134 $term->setlflag($oterm); 135 $term->setcc(VTIME, 0); 136 $term->setattr($fd_stdin, TCSANOW); 137 } 138 139 sub readkey { 140 my $key = ''; 141 cbreak(); 142 sysread(STDIN, $key, 1); 143 cooked(); 144 return $key; 145 } 146 147 END { cooked() } 148 149 1; 150 151=head2 How do I check whether input is ready on the keyboard? 152 153The easiest way to do this is to read a key in nonblocking mode with the 154Term::ReadKey module from CPAN, passing it an argument of -1 to indicate 155not to block: 156 157 use Term::ReadKey; 158 159 ReadMode('cbreak'); 160 161 if (defined ($char = ReadKey(-1)) ) { 162 # input was waiting and it was $char 163 } else { 164 # no input was waiting 165 } 166 167 ReadMode('normal'); # restore normal tty settings 168 169=head2 How do I clear the screen? 170 171If you only have do so infrequently, use C<system>: 172 173 system("clear"); 174 175If you have to do this a lot, save the clear string 176so you can print it 100 times without calling a program 177100 times: 178 179 $clear_string = `clear`; 180 print $clear_string; 181 182If you're planning on doing other screen manipulations, like cursor 183positions, etc, you might wish to use Term::Cap module: 184 185 use Term::Cap; 186 $terminal = Term::Cap->Tgetent( {OSPEED => 9600} ); 187 $clear_string = $terminal->Tputs('cl'); 188 189=head2 How do I get the screen size? 190 191If you have Term::ReadKey module installed from CPAN, 192you can use it to fetch the width and height in characters 193and in pixels: 194 195 use Term::ReadKey; 196 ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize(); 197 198This is more portable than the raw C<ioctl>, but not as 199illustrative: 200 201 require 'sys/ioctl.ph'; 202 die "no TIOCGWINSZ " unless defined &TIOCGWINSZ; 203 open(TTY, "+</dev/tty") or die "No tty: $!"; 204 unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) { 205 die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ; 206 } 207 ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize); 208 print "(row,col) = ($row,$col)"; 209 print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel; 210 print "\n"; 211 212=head2 How do I ask the user for a password? 213 214(This question has nothing to do with the web. See a different 215FAQ for that.) 216 217There's an example of this in L<perlfunc/crypt>). First, you put the 218terminal into "no echo" mode, then just read the password normally. 219You may do this with an old-style ioctl() function, POSIX terminal 220control (see L<POSIX> or its documentation the Camel Book), or a call 221to the B<stty> program, with varying degrees of portability. 222 223You can also do this for most systems using the Term::ReadKey module 224from CPAN, which is easier to use and in theory more portable. 225 226 use Term::ReadKey; 227 228 ReadMode('noecho'); 229 $password = ReadLine(0); 230 231=head2 How do I read and write the serial port? 232 233This depends on which operating system your program is running on. In 234the case of Unix, the serial ports will be accessible through files in 235/dev; on other systems, device names will doubtless differ. 236Several problem areas common to all device interaction are the 237following: 238 239=over 4 240 241=item lockfiles 242 243Your system may use lockfiles to control multiple access. Make sure 244you follow the correct protocol. Unpredictable behavior can result 245from multiple processes reading from one device. 246 247=item open mode 248 249If you expect to use both read and write operations on the device, 250you'll have to open it for update (see L<perlfunc/"open"> for 251details). You may wish to open it without running the risk of 252blocking by using sysopen() and C<O_RDWR|O_NDELAY|O_NOCTTY> from the 253Fcntl module (part of the standard perl distribution). See 254L<perlfunc/"sysopen"> for more on this approach. 255 256=item end of line 257 258Some devices will be expecting a "\r" at the end of each line rather 259than a "\n". In some ports of perl, "\r" and "\n" are different from 260their usual (Unix) ASCII values of "\012" and "\015". You may have to 261give the numeric values you want directly, using octal ("\015"), hex 262("0x0D"), or as a control-character specification ("\cM"). 263 264 print DEV "atv1\012"; # wrong, for some devices 265 print DEV "atv1\015"; # right, for some devices 266 267Even though with normal text files a "\n" will do the trick, there is 268still no unified scheme for terminating a line that is portable 269between Unix, DOS/Win, and Macintosh, except to terminate I<ALL> line 270ends with "\015\012", and strip what you don't need from the output. 271This applies especially to socket I/O and autoflushing, discussed 272next. 273 274=item flushing output 275 276If you expect characters to get to your device when you print() them, 277you'll want to autoflush that filehandle. You can use select() 278and the C<$|> variable to control autoflushing (see L<perlvar/$E<verbar>> 279and L<perlfunc/select>, or L<perlfaq5>, ``How do I flush/unbuffer an 280output filehandle? Why must I do this?''): 281 282 $oldh = select(DEV); 283 $| = 1; 284 select($oldh); 285 286You'll also see code that does this without a temporary variable, as in 287 288 select((select(DEV), $| = 1)[0]); 289 290Or if you don't mind pulling in a few thousand lines 291of code just because you're afraid of a little $| variable: 292 293 use IO::Handle; 294 DEV->autoflush(1); 295 296As mentioned in the previous item, this still doesn't work when using 297socket I/O between Unix and Macintosh. You'll need to hard code your 298line terminators, in that case. 299 300=item non-blocking input 301 302If you are doing a blocking read() or sysread(), you'll have to 303arrange for an alarm handler to provide a timeout (see 304L<perlfunc/alarm>). If you have a non-blocking open, you'll likely 305have a non-blocking read, which means you may have to use a 4-arg 306select() to determine whether I/O is ready on that device (see 307L<perlfunc/"select">. 308 309=back 310 311While trying to read from his caller-id box, the notorious Jamie Zawinski 312<jwz@netscape.com>, after much gnashing of teeth and fighting with sysread, 313sysopen, POSIX's tcgetattr business, and various other functions that 314go bump in the night, finally came up with this: 315 316 sub open_modem { 317 use IPC::Open2; 318 my $stty = `/bin/stty -g`; 319 open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1"); 320 # starting cu hoses /dev/tty's stty settings, even when it has 321 # been opened on a pipe... 322 system("/bin/stty $stty"); 323 $_ = <MODEM_IN>; 324 chomp; 325 if ( !m/^Connected/ ) { 326 print STDERR "$0: cu printed `$_' instead of `Connected'\n"; 327 } 328 } 329 330=head2 How do I decode encrypted password files? 331 332You spend lots and lots of money on dedicated hardware, but this is 333bound to get you talked about. 334 335Seriously, you can't if they are Unix password files--the Unix 336password system employs one-way encryption. It's more like hashing than 337encryption. The best you can check is whether something else hashes to 338the same string. You can't turn a hash back into the original string. 339Programs like Crack 340can forcibly (and intelligently) try to guess passwords, but don't 341(can't) guarantee quick success. 342 343If you're worried about users selecting bad passwords, you should 344proactively check when they try to change their password (by modifying 345passwd(1), for example). 346 347=head2 How do I start a process in the background? 348 349Several modules can start other processes that do not block 350your Perl program. You can use IPC::Open3, Parallel::Jobs, 351IPC::Run, and some of the POE modules. See CPAN for more 352details. 353 354You could also use 355 356 system("cmd &") 357 358or you could use fork as documented in L<perlfunc/"fork">, with 359further examples in L<perlipc>. Some things to be aware of, if you're 360on a Unix-like system: 361 362=over 4 363 364=item STDIN, STDOUT, and STDERR are shared 365 366Both the main process and the backgrounded one (the "child" process) 367share the same STDIN, STDOUT and STDERR filehandles. If both try to 368access them at once, strange things can happen. You may want to close 369or reopen these for the child. You can get around this with 370C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this 371means that the child process cannot outlive the parent. 372 373=item Signals 374 375You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too. 376SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is 377sent when you write to a filehandle whose child process has closed (an 378untrapped SIGPIPE can cause your program to silently die). This is 379not an issue with C<system("cmd&")>. 380 381=item Zombies 382 383You have to be prepared to "reap" the child process when it finishes. 384 385 $SIG{CHLD} = sub { wait }; 386 387 $SIG{CHLD} = 'IGNORE'; 388 389You can also use a double fork. You immediately wait() for your 390first child, and the init daemon will wait() for your grandchild once 391it exits. 392 393 unless ($pid = fork) { 394 unless (fork) { 395 exec "what you really wanna do"; 396 die "exec failed!"; 397 } 398 exit 0; 399 } 400 waitpid($pid,0); 401 402 403See L<perlipc/"Signals"> for other examples of code to do this. 404Zombies are not an issue with C<system("prog &")>. 405 406=back 407 408=head2 How do I trap control characters/signals? 409 410You don't actually "trap" a control character. Instead, that character 411generates a signal which is sent to your terminal's currently 412foregrounded process group, which you then trap in your process. 413Signals are documented in L<perlipc/"Signals"> and the 414section on ``Signals'' in the Camel. 415 416Be warned that very few C libraries are re-entrant. Therefore, if you 417attempt to print() in a handler that got invoked during another stdio 418operation your internal structures will likely be in an 419inconsistent state, and your program will dump core. You can 420sometimes avoid this by using syswrite() instead of print(). 421 422Unless you're exceedingly careful, the only safe things to do inside a 423signal handler are (1) set a variable and (2) exit. In the first case, 424you should only set a variable in such a way that malloc() is not 425called (eg, by setting a variable that already has a value). 426 427For example: 428 429 $Interrupted = 0; # to ensure it has a value 430 $SIG{INT} = sub { 431 $Interrupted++; 432 syswrite(STDERR, "ouch\n", 5); 433 } 434 435However, because syscalls restart by default, you'll find that if 436you're in a "slow" call, such as <FH>, read(), connect(), or 437wait(), that the only way to terminate them is by "longjumping" out; 438that is, by raising an exception. See the time-out handler for a 439blocking flock() in L<perlipc/"Signals"> or the section on ``Signals'' 440in the Camel book. 441 442=head2 How do I modify the shadow password file on a Unix system? 443 444If perl was installed correctly and your shadow library was written 445properly, the getpw*() functions described in L<perlfunc> should in 446theory provide (read-only) access to entries in the shadow password 447file. To change the file, make a new shadow password file (the format 448varies from system to system--see L<passwd> for specifics) and use 449pwd_mkdb(8) to install it (see L<pwd_mkdb> for more details). 450 451=head2 How do I set the time and date? 452 453Assuming you're running under sufficient permissions, you should be 454able to set the system-wide date and time by running the date(1) 455program. (There is no way to set the time and date on a per-process 456basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT; 457the VMS equivalent is C<set time>. 458 459However, if all you want to do is change your time zone, you can 460probably get away with setting an environment variable: 461 462 $ENV{TZ} = "MST7MDT"; # unixish 463 $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms 464 system "trn comp.lang.perl.misc"; 465 466=head2 How can I sleep() or alarm() for under a second? 467 468If you want finer granularity than the 1 second that the sleep() 469function provides, the easiest way is to use the select() function as 470documented in L<perlfunc/"select">. Try the Time::HiRes and 471the BSD::Itimer modules (available from CPAN, and starting from 472Perl 5.8 Time::HiRes is part of the standard distribution). 473 474=head2 How can I measure time under a second? 475 476In general, you may not be able to. The Time::HiRes module (available 477from CPAN, and starting from Perl 5.8 part of the standard distribution) 478provides this functionality for some systems. 479 480If your system supports both the syscall() function in Perl as well as 481a system call like gettimeofday(2), then you may be able to do 482something like this: 483 484 require 'sys/syscall.ph'; 485 486 $TIMEVAL_T = "LL"; 487 488 $done = $start = pack($TIMEVAL_T, ()); 489 490 syscall(&SYS_gettimeofday, $start, 0) != -1 491 or die "gettimeofday: $!"; 492 493 ########################## 494 # DO YOUR OPERATION HERE # 495 ########################## 496 497 syscall( &SYS_gettimeofday, $done, 0) != -1 498 or die "gettimeofday: $!"; 499 500 @start = unpack($TIMEVAL_T, $start); 501 @done = unpack($TIMEVAL_T, $done); 502 503 # fix microseconds 504 for ($done[1], $start[1]) { $_ /= 1_000_000 } 505 506 $delta_time = sprintf "%.4f", ($done[0] + $done[1] ) 507 - 508 ($start[0] + $start[1] ); 509 510=head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling) 511 512Release 5 of Perl added the END block, which can be used to simulate 513atexit(). Each package's END block is called when the program or 514thread ends (see L<perlmod> manpage for more details). 515 516For example, you can use this to make sure your filter program 517managed to finish its output without filling up the disk: 518 519 END { 520 close(STDOUT) || die "stdout close failed: $!"; 521 } 522 523The END block isn't called when untrapped signals kill the program, 524though, so if you use END blocks you should also use 525 526 use sigtrap qw(die normal-signals); 527 528Perl's exception-handling mechanism is its eval() operator. You can 529use eval() as setjmp and die() as longjmp. For details of this, see 530the section on signals, especially the time-out handler for a blocking 531flock() in L<perlipc/"Signals"> or the section on ``Signals'' in 532the Camel Book. 533 534If exception handling is all you're interested in, try the 535exceptions.pl library (part of the standard perl distribution). 536 537If you want the atexit() syntax (and an rmexit() as well), try the 538AtExit module available from CPAN. 539 540=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? 541 542Some Sys-V based systems, notably Solaris 2.X, redefined some of the 543standard socket constants. Since these were constant across all 544architectures, they were often hardwired into perl code. The proper 545way to deal with this is to "use Socket" to get the correct values. 546 547Note that even though SunOS and Solaris are binary compatible, these 548values are different. Go figure. 549 550=head2 How can I call my system's unique C functions from Perl? 551 552In most cases, you write an external module to do it--see the answer 553to "Where can I learn about linking C with Perl? [h2xs, xsubpp]". 554However, if the function is a system call, and your system supports 555syscall(), you can use the syscall function (documented in 556L<perlfunc>). 557 558Remember to check the modules that came with your distribution, and 559CPAN as well---someone may already have written a module to do it. On 560Windows, try Win32::API. On Macs, try Mac::Carbon. If no module 561has an interface to the C function, you can inline a bit of C in your 562Perl source with Inline::C. 563 564=head2 Where do I get the include files to do ioctl() or syscall()? 565 566Historically, these would be generated by the h2ph tool, part of the 567standard perl distribution. This program converts cpp(1) directives 568in C header files to files containing subroutine definitions, like 569&SYS_getitimer, which you can use as arguments to your functions. 570It doesn't work perfectly, but it usually gets most of the job done. 571Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine, 572but the hard ones like F<ioctl.h> nearly always need to hand-edited. 573Here's how to install the *.ph files: 574 575 1. become super-user 576 2. cd /usr/include 577 3. h2ph *.h */*.h 578 579If your system supports dynamic loading, for reasons of portability and 580sanity you probably ought to use h2xs (also part of the standard perl 581distribution). This tool converts C header files to Perl extensions. 582See L<perlxstut> for how to get started with h2xs. 583 584If your system doesn't support dynamic loading, you still probably 585ought to use h2xs. See L<perlxstut> and L<ExtUtils::MakeMaker> for 586more information (in brief, just use B<make perl> instead of a plain 587B<make> to rebuild perl with a new static extension). 588 589=head2 Why do setuid perl scripts complain about kernel problems? 590 591Some operating systems have bugs in the kernel that make setuid 592scripts inherently insecure. Perl gives you a number of options 593(described in L<perlsec>) to work around such systems. 594 595=head2 How can I open a pipe both to and from a command? 596 597The IPC::Open2 module (part of the standard perl distribution) is an 598easy-to-use approach that internally uses pipe(), fork(), and exec() to do 599the job. Make sure you read the deadlock warnings in its documentation, 600though (see L<IPC::Open2>). See 601L<perlipc/"Bidirectional Communication with Another Process"> and 602L<perlipc/"Bidirectional Communication with Yourself"> 603 604You may also use the IPC::Open3 module (part of the standard perl 605distribution), but be warned that it has a different order of 606arguments from IPC::Open2 (see L<IPC::Open3>). 607 608=head2 Why can't I get the output of a command with system()? 609 610You're confusing the purpose of system() and backticks (``). system() 611runs a command and returns exit status information (as a 16 bit value: 612the low 7 bits are the signal the process died from, if any, and 613the high 8 bits are the actual exit value). Backticks (``) run a 614command and return what it sent to STDOUT. 615 616 $exit_status = system("mail-users"); 617 $output_string = `ls`; 618 619=head2 How can I capture STDERR from an external command? 620 621There are three basic ways of running external commands: 622 623 system $cmd; # using system() 624 $output = `$cmd`; # using backticks (``) 625 open (PIPE, "cmd |"); # using open() 626 627With system(), both STDOUT and STDERR will go the same place as the 628script's STDOUT and STDERR, unless the system() command redirects them. 629Backticks and open() read B<only> the STDOUT of your command. 630 631You can also use the open3() function from IPC::Open3. Benjamin 632Goldberg provides some sample code: 633 634To capture a program's STDOUT, but discard its STDERR: 635 636 use IPC::Open3; 637 use File::Spec; 638 use Symbol qw(gensym); 639 open(NULL, ">", File::Spec->devnull); 640 my $pid = open3(gensym, \*PH, ">&NULL", "cmd"); 641 while( <PH> ) { } 642 waitpid($pid, 0); 643 644To capture a program's STDERR, but discard its STDOUT: 645 646 use IPC::Open3; 647 use File::Spec; 648 use Symbol qw(gensym); 649 open(NULL, ">", File::Spec->devnull); 650 my $pid = open3(gensym, ">&NULL", \*PH, "cmd"); 651 while( <PH> ) { } 652 waitpid($pid, 0); 653 654To capture a program's STDERR, and let its STDOUT go to our own STDERR: 655 656 use IPC::Open3; 657 use Symbol qw(gensym); 658 my $pid = open3(gensym, ">&STDERR", \*PH, "cmd"); 659 while( <PH> ) { } 660 waitpid($pid, 0); 661 662To read both a command's STDOUT and its STDERR separately, you can 663redirect them to temp files, let the command run, then read the temp 664files: 665 666 use IPC::Open3; 667 use Symbol qw(gensym); 668 use IO::File; 669 local *CATCHOUT = IO::File->new_tempfile; 670 local *CATCHERR = IO::File->new_tempfile; 671 my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd"); 672 waitpid($pid, 0); 673 seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR; 674 while( <CATCHOUT> ) {} 675 while( <CATCHERR> ) {} 676 677But there's no real need for *both* to be tempfiles... the following 678should work just as well, without deadlocking: 679 680 use IPC::Open3; 681 use Symbol qw(gensym); 682 use IO::File; 683 local *CATCHERR = IO::File->new_tempfile; 684 my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd"); 685 while( <CATCHOUT> ) {} 686 waitpid($pid, 0); 687 seek CATCHERR, 0, 0; 688 while( <CATCHERR> ) {} 689 690And it'll be faster, too, since we can begin processing the program's 691stdout immediately, rather than waiting for the program to finish. 692 693With any of these, you can change file descriptors before the call: 694 695 open(STDOUT, ">logfile"); 696 system("ls"); 697 698or you can use Bourne shell file-descriptor redirection: 699 700 $output = `$cmd 2>some_file`; 701 open (PIPE, "cmd 2>some_file |"); 702 703You can also use file-descriptor redirection to make STDERR a 704duplicate of STDOUT: 705 706 $output = `$cmd 2>&1`; 707 open (PIPE, "cmd 2>&1 |"); 708 709Note that you I<cannot> simply open STDERR to be a dup of STDOUT 710in your Perl program and avoid calling the shell to do the redirection. 711This doesn't work: 712 713 open(STDERR, ">&STDOUT"); 714 $alloutput = `cmd args`; # stderr still escapes 715 716This fails because the open() makes STDERR go to where STDOUT was 717going at the time of the open(). The backticks then make STDOUT go to 718a string, but don't change STDERR (which still goes to the old 719STDOUT). 720 721Note that you I<must> use Bourne shell (sh(1)) redirection syntax in 722backticks, not csh(1)! Details on why Perl's system() and backtick 723and pipe opens all use the Bourne shell are in the 724F<versus/csh.whynot> article in the "Far More Than You Ever Wanted To 725Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . To 726capture a command's STDERR and STDOUT together: 727 728 $output = `cmd 2>&1`; # either with backticks 729 $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe 730 while (<PH>) { } # plus a read 731 732To capture a command's STDOUT but discard its STDERR: 733 734 $output = `cmd 2>/dev/null`; # either with backticks 735 $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe 736 while (<PH>) { } # plus a read 737 738To capture a command's STDERR but discard its STDOUT: 739 740 $output = `cmd 2>&1 1>/dev/null`; # either with backticks 741 $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe 742 while (<PH>) { } # plus a read 743 744To exchange a command's STDOUT and STDERR in order to capture the STDERR 745but leave its STDOUT to come out our old STDERR: 746 747 $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks 748 $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe 749 while (<PH>) { } # plus a read 750 751To read both a command's STDOUT and its STDERR separately, it's easiest 752to redirect them separately to files, and then read from those files 753when the program is done: 754 755 system("program args 1>program.stdout 2>program.stderr"); 756 757Ordering is important in all these examples. That's because the shell 758processes file descriptor redirections in strictly left to right order. 759 760 system("prog args 1>tmpfile 2>&1"); 761 system("prog args 2>&1 1>tmpfile"); 762 763The first command sends both standard out and standard error to the 764temporary file. The second command sends only the old standard output 765there, and the old standard error shows up on the old standard out. 766 767=head2 Why doesn't open() return an error when a pipe open fails? 768 769If the second argument to a piped open() contains shell 770metacharacters, perl fork()s, then exec()s a shell to decode the 771metacharacters and eventually run the desired program. If the program 772couldn't be run, it's the shell that gets the message, not Perl. All 773your Perl program can find out is whether the shell itself could be 774successfully started. You can still capture the shell's STDERR and 775check it for error messages. See L<"How can I capture STDERR from an 776external command?"> elsewhere in this document, or use the 777IPC::Open3 module. 778 779If there are no shell metacharacters in the argument of open(), Perl 780runs the command directly, without using the shell, and can correctly 781report whether the command started. 782 783=head2 What's wrong with using backticks in a void context? 784 785Strictly speaking, nothing. Stylistically speaking, it's not a good 786way to write maintainable code. Perl has several operators for 787running external commands. Backticks are one; they collect the output 788from the command for use in your program. The C<system> function is 789another; it doesn't do this. 790 791Writing backticks in your program sends a clear message to the readers 792of your code that you wanted to collect the output of the command. 793Why send a clear message that isn't true? 794 795Consider this line: 796 797 `cat /etc/termcap`; 798 799You forgot to check C<$?> to see whether the program even ran 800correctly. Even if you wrote 801 802 print `cat /etc/termcap`; 803 804this code could and probably should be written as 805 806 system("cat /etc/termcap") == 0 807 or die "cat program failed!"; 808 809which will get the output quickly (as it is generated, instead of only 810at the end) and also check the return value. 811 812system() also provides direct control over whether shell wildcard 813processing may take place, whereas backticks do not. 814 815=head2 How can I call backticks without shell processing? 816 817This is a bit tricky. You can't simply write the command 818like this: 819 820 @ok = `grep @opts '$search_string' @filenames`; 821 822As of Perl 5.8.0, you can use open() with multiple arguments. 823Just like the list forms of system() and exec(), no shell 824escapes happen. 825 826 open( GREP, "-|", 'grep', @opts, $search_string, @filenames ); 827 chomp(@ok = <GREP>); 828 close GREP; 829 830You can also: 831 832 my @ok = (); 833 if (open(GREP, "-|")) { 834 while (<GREP>) { 835 chomp; 836 push(@ok, $_); 837 } 838 close GREP; 839 } else { 840 exec 'grep', @opts, $search_string, @filenames; 841 } 842 843Just as with system(), no shell escapes happen when you exec() a list. 844Further examples of this can be found in L<perlipc/"Safe Pipe Opens">. 845 846Note that if you're use Microsoft, no solution to this vexing issue 847is even possible. Even if Perl were to emulate fork(), you'd still 848be stuck, because Microsoft does not have a argc/argv-style API. 849 850=head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)? 851 852Some stdio's set error and eof flags that need clearing. The 853POSIX module defines clearerr() that you can use. That is the 854technically correct way to do it. Here are some less reliable 855workarounds: 856 857=over 4 858 859=item 1 860 861Try keeping around the seekpointer and go there, like this: 862 863 $where = tell(LOG); 864 seek(LOG, $where, 0); 865 866=item 2 867 868If that doesn't work, try seeking to a different part of the file and 869then back. 870 871=item 3 872 873If that doesn't work, try seeking to a different part of 874the file, reading something, and then seeking back. 875 876=item 4 877 878If that doesn't work, give up on your stdio package and use sysread. 879 880=back 881 882=head2 How can I convert my shell script to perl? 883 884Learn Perl and rewrite it. Seriously, there's no simple converter. 885Things that are awkward to do in the shell are easy to do in Perl, and 886this very awkwardness is what would make a shell->perl converter 887nigh-on impossible to write. By rewriting it, you'll think about what 888you're really trying to do, and hopefully will escape the shell's 889pipeline datastream paradigm, which while convenient for some matters, 890causes many inefficiencies. 891 892=head2 Can I use perl to run a telnet or ftp session? 893 894Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from 895CPAN). http://www.cpan.org/scripts/netstuff/telnet.emul.shar 896will also help for emulating the telnet protocol, but Net::Telnet is 897quite probably easier to use.. 898 899If all you want to do is pretend to be telnet but don't need 900the initial telnet handshaking, then the standard dual-process 901approach will suffice: 902 903 use IO::Socket; # new in 5.004 904 $handle = IO::Socket::INET->new('www.perl.com:80') 905 || die "can't connect to port 80 on www.perl.com: $!"; 906 $handle->autoflush(1); 907 if (fork()) { # XXX: undef means failure 908 select($handle); 909 print while <STDIN>; # everything from stdin to socket 910 } else { 911 print while <$handle>; # everything from socket to stdout 912 } 913 close $handle; 914 exit; 915 916=head2 How can I write expect in Perl? 917 918Once upon a time, there was a library called chat2.pl (part of the 919standard perl distribution), which never really got finished. If you 920find it somewhere, I<don't use it>. These days, your best bet is to 921look at the Expect module available from CPAN, which also requires two 922other modules from CPAN, IO::Pty and IO::Stty. 923 924=head2 Is there a way to hide perl's command line from programs such as "ps"? 925 926First of all note that if you're doing this for security reasons (to 927avoid people seeing passwords, for example) then you should rewrite 928your program so that critical information is never given as an 929argument. Hiding the arguments won't make your program completely 930secure. 931 932To actually alter the visible command line, you can assign to the 933variable $0 as documented in L<perlvar>. This won't work on all 934operating systems, though. Daemon programs like sendmail place their 935state there, as in: 936 937 $0 = "orcus [accepting connections]"; 938 939=head2 I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible? 940 941=over 4 942 943=item Unix 944 945In the strictest sense, it can't be done--the script executes as a 946different process from the shell it was started from. Changes to a 947process are not reflected in its parent--only in any children 948created after the change. There is shell magic that may allow you to 949fake it by eval()ing the script's output in your shell; check out the 950comp.unix.questions FAQ for details. 951 952=back 953 954=head2 How do I close a process's filehandle without waiting for it to complete? 955 956Assuming your system supports such things, just send an appropriate signal 957to the process (see L<perlfunc/"kill">). It's common to first send a TERM 958signal, wait a little bit, and then send a KILL signal to finish it off. 959 960=head2 How do I fork a daemon process? 961 962If by daemon process you mean one that's detached (disassociated from 963its tty), then the following process is reported to work on most 964Unixish systems. Non-Unix users should check their Your_OS::Process 965module for other solutions. 966 967=over 4 968 969=item * 970 971Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty> 972for details. Or better yet, you can just use the POSIX::setsid() 973function, so you don't have to worry about process groups. 974 975=item * 976 977Change directory to / 978 979=item * 980 981Reopen STDIN, STDOUT, and STDERR so they're not connected to the old 982tty. 983 984=item * 985 986Background yourself like this: 987 988 fork && exit; 989 990=back 991 992The Proc::Daemon module, available from CPAN, provides a function to 993perform these actions for you. 994 995=head2 How do I find out if I'm running interactively or not? 996 997Good question. Sometimes C<-t STDIN> and C<-t STDOUT> can give clues, 998sometimes not. 999 1000 if (-t STDIN && -t STDOUT) { 1001 print "Now what? "; 1002 } 1003 1004On POSIX systems, you can test whether your own process group matches 1005the current process group of your controlling terminal as follows: 1006 1007 use POSIX qw/getpgrp tcgetpgrp/; 1008 open(TTY, "/dev/tty") or die $!; 1009 $tpgrp = tcgetpgrp(fileno(*TTY)); 1010 $pgrp = getpgrp(); 1011 if ($tpgrp == $pgrp) { 1012 print "foreground\n"; 1013 } else { 1014 print "background\n"; 1015 } 1016 1017=head2 How do I timeout a slow event? 1018 1019Use the alarm() function, probably in conjunction with a signal 1020handler, as documented in L<perlipc/"Signals"> and the section on 1021``Signals'' in the Camel. You may instead use the more flexible 1022Sys::AlarmCall module available from CPAN. 1023 1024The alarm() function is not implemented on all versions of Windows. 1025Check the documentation for your specific version of Perl. 1026 1027=head2 How do I set CPU limits? 1028 1029Use the BSD::Resource module from CPAN. 1030 1031=head2 How do I avoid zombies on a Unix system? 1032 1033Use the reaper code from L<perlipc/"Signals"> to call wait() when a 1034SIGCHLD is received, or else use the double-fork technique described 1035in L<perlfaq8/"How do I start a process in the background?">. 1036 1037=head2 How do I use an SQL database? 1038 1039The DBI module provides an abstract interface to most database 1040servers and types, including Oracle, DB2, Sybase, mysql, Postgresql, 1041ODBC, and flat files. The DBI module accesses each database type 1042through a database driver, or DBD. You can see a complete list of 1043available drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ . 1044You can read more about DBI on http://dbi.perl.org . 1045 1046Other modules provide more specific access: Win32::ODBC, Alzabo, iodbc, 1047and others found on CPAN Search: http://search.cpan.org . 1048 1049=head2 How do I make a system() exit on control-C? 1050 1051You can't. You need to imitate the system() call (see L<perlipc> for 1052sample code) and then have a signal handler for the INT signal that 1053passes the signal on to the subprocess. Or you can check for it: 1054 1055 $rc = system($cmd); 1056 if ($rc & 127) { die "signal death" } 1057 1058=head2 How do I open a file without blocking? 1059 1060If you're lucky enough to be using a system that supports 1061non-blocking reads (most Unixish systems do), you need only to use the 1062O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with 1063sysopen(): 1064 1065 use Fcntl; 1066 sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644) 1067 or die "can't open /foo/somefile: $!": 1068 1069=head2 How do I install a module from CPAN? 1070 1071The easiest way is to have a module also named CPAN do it for you. 1072This module comes with perl version 5.004 and later. 1073 1074 $ perl -MCPAN -e shell 1075 1076 cpan shell -- CPAN exploration and modules installation (v1.59_54) 1077 ReadLine support enabled 1078 1079 cpan> install Some::Module 1080 1081To manually install the CPAN module, or any well-behaved CPAN module 1082for that matter, follow these steps: 1083 1084=over 4 1085 1086=item 1 1087 1088Unpack the source into a temporary area. 1089 1090=item 2 1091 1092 perl Makefile.PL 1093 1094=item 3 1095 1096 make 1097 1098=item 4 1099 1100 make test 1101 1102=item 5 1103 1104 make install 1105 1106=back 1107 1108If your version of perl is compiled without dynamic loading, then you 1109just need to replace step 3 (B<make>) with B<make perl> and you will 1110get a new F<perl> binary with your extension linked in. 1111 1112See L<ExtUtils::MakeMaker> for more details on building extensions. 1113See also the next question, ``What's the difference between require 1114and use?''. 1115 1116=head2 What's the difference between require and use? 1117 1118Perl offers several different ways to include code from one file into 1119another. Here are the deltas between the various inclusion constructs: 1120 1121 1) do $file is like eval `cat $file`, except the former 1122 1.1: searches @INC and updates %INC. 1123 1.2: bequeaths an *unrelated* lexical scope on the eval'ed code. 1124 1125 2) require $file is like do $file, except the former 1126 2.1: checks for redundant loading, skipping already loaded files. 1127 2.2: raises an exception on failure to find, compile, or execute $file. 1128 1129 3) require Module is like require "Module.pm", except the former 1130 3.1: translates each "::" into your system's directory separator. 1131 3.2: primes the parser to disambiguate class Module as an indirect object. 1132 1133 4) use Module is like require Module, except the former 1134 4.1: loads the module at compile time, not run-time. 1135 4.2: imports symbols and semantics from that package to the current one. 1136 1137In general, you usually want C<use> and a proper Perl module. 1138 1139=head2 How do I keep my own module/library directory? 1140 1141When you build modules, use the PREFIX and LIB options when generating 1142Makefiles: 1143 1144 perl Makefile.PL PREFIX=/mydir/perl LIB=/mydir/perl/lib 1145 1146then either set the PERL5LIB environment variable before you run 1147scripts that use the modules/libraries (see L<perlrun>) or say 1148 1149 use lib '/mydir/perl/lib'; 1150 1151This is almost the same as 1152 1153 BEGIN { 1154 unshift(@INC, '/mydir/perl/lib'); 1155 } 1156 1157except that the lib module checks for machine-dependent subdirectories. 1158See Perl's L<lib> for more information. 1159 1160=head2 How do I add the directory my program lives in to the module/library search path? 1161 1162 use FindBin; 1163 use lib "$FindBin::Bin"; 1164 use your_own_modules; 1165 1166=head2 How do I add a directory to my include path (@INC) at runtime? 1167 1168Here are the suggested ways of modifying your include path: 1169 1170 the PERLLIB environment variable 1171 the PERL5LIB environment variable 1172 the perl -Idir command line flag 1173 the use lib pragma, as in 1174 use lib "$ENV{HOME}/myown_perllib"; 1175 1176The latter is particularly useful because it knows about machine 1177dependent architectures. The lib.pm pragmatic module was first 1178included with the 5.002 release of Perl. 1179 1180=head2 What is socket.ph and where do I get it? 1181 1182It's a perl4-style file defining values for system networking 1183constants. Sometimes it is built using h2ph when Perl is installed, 1184but other times it is not. Modern programs C<use Socket;> instead. 1185 1186=head1 AUTHOR AND COPYRIGHT 1187 1188Copyright (c) 1997-2003 Tom Christiansen and Nathan Torkington. 1189All rights reserved. 1190 1191This documentation is free; you can redistribute it and/or modify it 1192under the same terms as Perl itself. 1193 1194Irrespective of its distribution, all code examples in this file 1195are hereby placed into the public domain. You are permitted and 1196encouraged to use this code in your own programs for fun 1197or for profit as you see fit. A simple comment in the code giving 1198credit would be courteous but is not required. 1199