Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1098 lines
37 KiB

  1. =head1 NAME
  2. perlfaq8 - System Interaction ($Revision: 1.36 $, $Date: 1999/01/08 05:36:34 $)
  3. =head1 DESCRIPTION
  4. This section of the Perl FAQ covers questions involving operating
  5. system interaction. This involves interprocess communication (IPC),
  6. control over the user-interface (keyboard, screen and pointing
  7. devices), and most anything else not related to data manipulation.
  8. Read the FAQs and documentation specific to the port of perl to your
  9. operating system (eg, L<perlvms>, L<perlplan9>, ...). These should
  10. contain more detailed information on the vagaries of your perl.
  11. =head2 How do I find out which operating system I'm running under?
  12. The $^O variable ($OSNAME if you use English) contains the operating
  13. system that your perl binary was built for.
  14. =head2 How come exec() doesn't return?
  15. Because that's what it does: it replaces your currently running
  16. program with a different one. If you want to keep going (as is
  17. probably the case if you're asking this question) use system()
  18. instead.
  19. =head2 How do I do fancy stuff with the keyboard/screen/mouse?
  20. How you access/control keyboards, screens, and pointing devices
  21. ("mice") is system-dependent. Try the following modules:
  22. =over 4
  23. =item Keyboard
  24. Term::Cap Standard perl distribution
  25. Term::ReadKey CPAN
  26. Term::ReadLine::Gnu CPAN
  27. Term::ReadLine::Perl CPAN
  28. Term::Screen CPAN
  29. =item Screen
  30. Term::Cap Standard perl distribution
  31. Curses CPAN
  32. Term::ANSIColor CPAN
  33. =item Mouse
  34. Tk CPAN
  35. =back
  36. Some of these specific cases are shown below.
  37. =head2 How do I print something out in color?
  38. In general, you don't, because you don't know whether
  39. the recipient has a color-aware display device. If you
  40. know that they have an ANSI terminal that understands
  41. color, you can use the Term::ANSIColor module from CPAN:
  42. use Term::ANSIColor;
  43. print color("red"), "Stop!\n", color("reset");
  44. print color("green"), "Go!\n", color("reset");
  45. Or like this:
  46. use Term::ANSIColor qw(:constants);
  47. print RED, "Stop!\n", RESET;
  48. print GREEN, "Go!\n", RESET;
  49. =head2 How do I read just one key without waiting for a return key?
  50. Controlling input buffering is a remarkably system-dependent matter.
  51. If most systems, you can just use the B<stty> command as shown in
  52. L<perlfunc/getc>, but as you see, that's already getting you into
  53. portability snags.
  54. open(TTY, "+</dev/tty") or die "no tty: $!";
  55. system "stty cbreak </dev/tty >/dev/tty 2>&1";
  56. $key = getc(TTY); # perhaps this works
  57. # OR ELSE
  58. sysread(TTY, $key, 1); # probably this does
  59. system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  60. The Term::ReadKey module from CPAN offers an easy-to-use interface that
  61. should be more efficient than shelling out to B<stty> for each key.
  62. It even includes limited support for Windows.
  63. use Term::ReadKey;
  64. ReadMode('cbreak');
  65. $key = ReadKey(0);
  66. ReadMode('normal');
  67. However, that requires that you have a working C compiler and can use it
  68. to build and install a CPAN module. Here's a solution using
  69. the standard POSIX module, which is already on your systems (assuming
  70. your system supports POSIX).
  71. use HotKey;
  72. $key = readkey();
  73. And here's the HotKey module, which hides the somewhat mystifying calls
  74. to manipulate the POSIX termios structures.
  75. # HotKey.pm
  76. package HotKey;
  77. @ISA = qw(Exporter);
  78. @EXPORT = qw(cbreak cooked readkey);
  79. use strict;
  80. use POSIX qw(:termios_h);
  81. my ($term, $oterm, $echo, $noecho, $fd_stdin);
  82. $fd_stdin = fileno(STDIN);
  83. $term = POSIX::Termios->new();
  84. $term->getattr($fd_stdin);
  85. $oterm = $term->getlflag();
  86. $echo = ECHO | ECHOK | ICANON;
  87. $noecho = $oterm & ~$echo;
  88. sub cbreak {
  89. $term->setlflag($noecho); # ok, so i don't want echo either
  90. $term->setcc(VTIME, 1);
  91. $term->setattr($fd_stdin, TCSANOW);
  92. }
  93. sub cooked {
  94. $term->setlflag($oterm);
  95. $term->setcc(VTIME, 0);
  96. $term->setattr($fd_stdin, TCSANOW);
  97. }
  98. sub readkey {
  99. my $key = '';
  100. cbreak();
  101. sysread(STDIN, $key, 1);
  102. cooked();
  103. return $key;
  104. }
  105. END { cooked() }
  106. 1;
  107. =head2 How do I check whether input is ready on the keyboard?
  108. The easiest way to do this is to read a key in nonblocking mode with the
  109. Term::ReadKey module from CPAN, passing it an argument of -1 to indicate
  110. not to block:
  111. use Term::ReadKey;
  112. ReadMode('cbreak');
  113. if (defined ($char = ReadKey(-1)) ) {
  114. # input was waiting and it was $char
  115. } else {
  116. # no input was waiting
  117. }
  118. ReadMode('normal'); # restore normal tty settings
  119. =head2 How do I clear the screen?
  120. If you only have to so infrequently, use C<system>:
  121. system("clear");
  122. If you have to do this a lot, save the clear string
  123. so you can print it 100 times without calling a program
  124. 100 times:
  125. $clear_string = `clear`;
  126. print $clear_string;
  127. If you're planning on doing other screen manipulations, like cursor
  128. positions, etc, you might wish to use Term::Cap module:
  129. use Term::Cap;
  130. $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
  131. $clear_string = $terminal->Tputs('cl');
  132. =head2 How do I get the screen size?
  133. If you have Term::ReadKey module installed from CPAN,
  134. you can use it to fetch the width and height in characters
  135. and in pixels:
  136. use Term::ReadKey;
  137. ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
  138. This is more portable than the raw C<ioctl>, but not as
  139. illustrative:
  140. require 'sys/ioctl.ph';
  141. die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
  142. open(TTY, "+</dev/tty") or die "No tty: $!";
  143. unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
  144. die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
  145. }
  146. ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
  147. print "(row,col) = ($row,$col)";
  148. print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
  149. print "\n";
  150. =head2 How do I ask the user for a password?
  151. (This question has nothing to do with the web. See a different
  152. FAQ for that.)
  153. There's an example of this in L<perlfunc/crypt>). First, you put
  154. the terminal into "no echo" mode, then just read the password
  155. normally. You may do this with an old-style ioctl() function, POSIX
  156. terminal control (see L<POSIX>, and Chapter 7 of the Camel), or a call
  157. to the B<stty> program, with varying degrees of portability.
  158. You can also do this for most systems using the Term::ReadKey module
  159. from CPAN, which is easier to use and in theory more portable.
  160. use Term::ReadKey;
  161. ReadMode('noecho');
  162. $password = ReadLine(0);
  163. =head2 How do I read and write the serial port?
  164. This depends on which operating system your program is running on. In
  165. the case of Unix, the serial ports will be accessible through files in
  166. /dev; on other systems, the devices names will doubtless differ.
  167. Several problem areas common to all device interaction are the
  168. following
  169. =over 4
  170. =item lockfiles
  171. Your system may use lockfiles to control multiple access. Make sure
  172. you follow the correct protocol. Unpredictable behaviour can result
  173. from multiple processes reading from one device.
  174. =item open mode
  175. If you expect to use both read and write operations on the device,
  176. you'll have to open it for update (see L<perlfunc/"open"> for
  177. details). You may wish to open it without running the risk of
  178. blocking by using sysopen() and C<O_RDWR|O_NDELAY|O_NOCTTY> from the
  179. Fcntl module (part of the standard perl distribution). See
  180. L<perlfunc/"sysopen"> for more on this approach.
  181. =item end of line
  182. Some devices will be expecting a "\r" at the end of each line rather
  183. than a "\n". In some ports of perl, "\r" and "\n" are different from
  184. their usual (Unix) ASCII values of "\012" and "\015". You may have to
  185. give the numeric values you want directly, using octal ("\015"), hex
  186. ("0x0D"), or as a control-character specification ("\cM").
  187. print DEV "atv1\012"; # wrong, for some devices
  188. print DEV "atv1\015"; # right, for some devices
  189. Even though with normal text files, a "\n" will do the trick, there is
  190. still no unified scheme for terminating a line that is portable
  191. between Unix, DOS/Win, and Macintosh, except to terminate I<ALL> line
  192. ends with "\015\012", and strip what you don't need from the output.
  193. This applies especially to socket I/O and autoflushing, discussed
  194. next.
  195. =item flushing output
  196. If you expect characters to get to your device when you print() them,
  197. you'll want to autoflush that filehandle. You can use select()
  198. and the C<$|> variable to control autoflushing (see L<perlvar/$|>
  199. and L<perlfunc/select>):
  200. $oldh = select(DEV);
  201. $| = 1;
  202. select($oldh);
  203. You'll also see code that does this without a temporary variable, as in
  204. select((select(DEV), $| = 1)[0]);
  205. Or if you don't mind pulling in a few thousand lines
  206. of code just because you're afraid of a little $| variable:
  207. use IO::Handle;
  208. DEV->autoflush(1);
  209. As mentioned in the previous item, this still doesn't work when using
  210. socket I/O between Unix and Macintosh. You'll need to hardcode your
  211. line terminators, in that case.
  212. =item non-blocking input
  213. If you are doing a blocking read() or sysread(), you'll have to
  214. arrange for an alarm handler to provide a timeout (see
  215. L<perlfunc/alarm>). If you have a non-blocking open, you'll likely
  216. have a non-blocking read, which means you may have to use a 4-arg
  217. select() to determine whether I/O is ready on that device (see
  218. L<perlfunc/"select">.
  219. =back
  220. While trying to read from his caller-id box, the notorious Jamie Zawinski
  221. <[email protected]>, after much gnashing of teeth and fighting with sysread,
  222. sysopen, POSIX's tcgetattr business, and various other functions that
  223. go bump in the night, finally came up with this:
  224. sub open_modem {
  225. use IPC::Open2;
  226. my $stty = `/bin/stty -g`;
  227. open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
  228. # starting cu hoses /dev/tty's stty settings, even when it has
  229. # been opened on a pipe...
  230. system("/bin/stty $stty");
  231. $_ = <MODEM_IN>;
  232. chop;
  233. if ( !m/^Connected/ ) {
  234. print STDERR "$0: cu printed `$_' instead of `Connected'\n";
  235. }
  236. }
  237. =head2 How do I decode encrypted password files?
  238. You spend lots and lots of money on dedicated hardware, but this is
  239. bound to get you talked about.
  240. Seriously, you can't if they are Unix password files - the Unix
  241. password system employs one-way encryption. It's more like hashing than
  242. encryption. The best you can check is whether something else hashes to
  243. the same string. You can't turn a hash back into the original string.
  244. Programs like Crack
  245. can forcibly (and intelligently) try to guess passwords, but don't
  246. (can't) guarantee quick success.
  247. If you're worried about users selecting bad passwords, you should
  248. proactively check when they try to change their password (by modifying
  249. passwd(1), for example).
  250. =head2 How do I start a process in the background?
  251. You could use
  252. system("cmd &")
  253. or you could use fork as documented in L<perlfunc/"fork">, with
  254. further examples in L<perlipc>. Some things to be aware of, if you're
  255. on a Unix-like system:
  256. =over 4
  257. =item STDIN, STDOUT, and STDERR are shared
  258. Both the main process and the backgrounded one (the "child" process)
  259. share the same STDIN, STDOUT and STDERR filehandles. If both try to
  260. access them at once, strange things can happen. You may want to close
  261. or reopen these for the child. You can get around this with
  262. C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this
  263. means that the child process cannot outlive the parent.
  264. =item Signals
  265. You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
  266. SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
  267. sent when you write to a filehandle whose child process has closed (an
  268. untrapped SIGPIPE can cause your program to silently die). This is
  269. not an issue with C<system("cmd&")>.
  270. =item Zombies
  271. You have to be prepared to "reap" the child process when it finishes
  272. $SIG{CHLD} = sub { wait };
  273. See L<perlipc/"Signals"> for other examples of code to do this.
  274. Zombies are not an issue with C<system("prog &")>.
  275. =back
  276. =head2 How do I trap control characters/signals?
  277. You don't actually "trap" a control character. Instead, that character
  278. generates a signal which is sent to your terminal's currently
  279. foregrounded process group, which you then trap in your process.
  280. Signals are documented in L<perlipc/"Signals"> and chapter 6 of the Camel.
  281. Be warned that very few C libraries are re-entrant. Therefore, if you
  282. attempt to print() in a handler that got invoked during another stdio
  283. operation your internal structures will likely be in an
  284. inconsistent state, and your program will dump core. You can
  285. sometimes avoid this by using syswrite() instead of print().
  286. Unless you're exceedingly careful, the only safe things to do inside a
  287. signal handler are: set a variable and exit. And in the first case,
  288. you should only set a variable in such a way that malloc() is not
  289. called (eg, by setting a variable that already has a value).
  290. For example:
  291. $Interrupted = 0; # to ensure it has a value
  292. $SIG{INT} = sub {
  293. $Interrupted++;
  294. syswrite(STDERR, "ouch\n", 5);
  295. }
  296. However, because syscalls restart by default, you'll find that if
  297. you're in a "slow" call, such as E<lt>FHE<gt>, read(), connect(), or
  298. wait(), that the only way to terminate them is by "longjumping" out;
  299. that is, by raising an exception. See the time-out handler for a
  300. blocking flock() in L<perlipc/"Signals"> or chapter 6 of the Camel.
  301. =head2 How do I modify the shadow password file on a Unix system?
  302. If perl was installed correctly, and your shadow library was written
  303. properly, the getpw*() functions described in L<perlfunc> should in
  304. theory provide (read-only) access to entries in the shadow password
  305. file. To change the file, make a new shadow password file (the format
  306. varies from system to system - see L<passwd(5)> for specifics) and use
  307. pwd_mkdb(8) to install it (see L<pwd_mkdb(5)> for more details).
  308. =head2 How do I set the time and date?
  309. Assuming you're running under sufficient permissions, you should be
  310. able to set the system-wide date and time by running the date(1)
  311. program. (There is no way to set the time and date on a per-process
  312. basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;
  313. the VMS equivalent is C<set time>.
  314. However, if all you want to do is change your timezone, you can
  315. probably get away with setting an environment variable:
  316. $ENV{TZ} = "MST7MDT"; # unixish
  317. $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
  318. system "trn comp.lang.perl.misc";
  319. =head2 How can I sleep() or alarm() for under a second?
  320. If you want finer granularity than the 1 second that the sleep()
  321. function provides, the easiest way is to use the select() function as
  322. documented in L<perlfunc/"select">. If your system has itimers and
  323. syscall() support, you can check out the old example in
  324. http://www.perl.com/CPAN/doc/misc/ancient/tutorial/eg/itimers.pl .
  325. =head2 How can I measure time under a second?
  326. In general, you may not be able to. The Time::HiRes module (available
  327. from CPAN) provides this functionality for some systems.
  328. If your system supports both the syscall() function in Perl as well as
  329. a system call like gettimeofday(2), then you may be able to do
  330. something like this:
  331. require 'sys/syscall.ph';
  332. $TIMEVAL_T = "LL";
  333. $done = $start = pack($TIMEVAL_T, ());
  334. syscall( &SYS_gettimeofday, $start, 0) != -1
  335. or die "gettimeofday: $!";
  336. ##########################
  337. # DO YOUR OPERATION HERE #
  338. ##########################
  339. syscall( &SYS_gettimeofday, $done, 0) != -1
  340. or die "gettimeofday: $!";
  341. @start = unpack($TIMEVAL_T, $start);
  342. @done = unpack($TIMEVAL_T, $done);
  343. # fix microseconds
  344. for ($done[1], $start[1]) { $_ /= 1_000_000 }
  345. $delta_time = sprintf "%.4f", ($done[0] + $done[1] )
  346. -
  347. ($start[0] + $start[1] );
  348. =head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
  349. Release 5 of Perl added the END block, which can be used to simulate
  350. atexit(). Each package's END block is called when the program or
  351. thread ends (see L<perlmod> manpage for more details).
  352. For example, you can use this to make sure your filter program
  353. managed to finish its output without filling up the disk:
  354. END {
  355. close(STDOUT) || die "stdout close failed: $!";
  356. }
  357. The END block isn't called when untrapped signals kill the program, though, so if
  358. you use END blocks you should also use
  359. use sigtrap qw(die normal-signals);
  360. Perl's exception-handling mechanism is its eval() operator. You can
  361. use eval() as setjmp and die() as longjmp. For details of this, see
  362. the section on signals, especially the time-out handler for a blocking
  363. flock() in L<perlipc/"Signals"> and chapter 6 of the Camel.
  364. If exception handling is all you're interested in, try the
  365. exceptions.pl library (part of the standard perl distribution).
  366. If you want the atexit() syntax (and an rmexit() as well), try the
  367. AtExit module available from CPAN.
  368. =head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
  369. Some Sys-V based systems, notably Solaris 2.X, redefined some of the
  370. standard socket constants. Since these were constant across all
  371. architectures, they were often hardwired into perl code. The proper
  372. way to deal with this is to "use Socket" to get the correct values.
  373. Note that even though SunOS and Solaris are binary compatible, these
  374. values are different. Go figure.
  375. =head2 How can I call my system's unique C functions from Perl?
  376. In most cases, you write an external module to do it - see the answer
  377. to "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
  378. However, if the function is a system call, and your system supports
  379. syscall(), you can use the syscall function (documented in
  380. L<perlfunc>).
  381. Remember to check the modules that came with your distribution, and
  382. CPAN as well - someone may already have written a module to do it.
  383. =head2 Where do I get the include files to do ioctl() or syscall()?
  384. Historically, these would be generated by the h2ph tool, part of the
  385. standard perl distribution. This program converts cpp(1) directives
  386. in C header files to files containing subroutine definitions, like
  387. &SYS_getitimer, which you can use as arguments to your functions.
  388. It doesn't work perfectly, but it usually gets most of the job done.
  389. Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine,
  390. but the hard ones like F<ioctl.h> nearly always need to hand-edited.
  391. Here's how to install the *.ph files:
  392. 1. become super-user
  393. 2. cd /usr/include
  394. 3. h2ph *.h */*.h
  395. If your system supports dynamic loading, for reasons of portability and
  396. sanity you probably ought to use h2xs (also part of the standard perl
  397. distribution). This tool converts C header files to Perl extensions.
  398. See L<perlxstut> for how to get started with h2xs.
  399. If your system doesn't support dynamic loading, you still probably
  400. ought to use h2xs. See L<perlxstut> and L<ExtUtils::MakeMaker> for
  401. more information (in brief, just use B<make perl> instead of a plain
  402. B<make> to rebuild perl with a new static extension).
  403. =head2 Why do setuid perl scripts complain about kernel problems?
  404. Some operating systems have bugs in the kernel that make setuid
  405. scripts inherently insecure. Perl gives you a number of options
  406. (described in L<perlsec>) to work around such systems.
  407. =head2 How can I open a pipe both to and from a command?
  408. The IPC::Open2 module (part of the standard perl distribution) is an
  409. easy-to-use approach that internally uses pipe(), fork(), and exec() to do
  410. the job. Make sure you read the deadlock warnings in its documentation,
  411. though (see L<IPC::Open2>). See L<perlipc/"Bidirectional Communication
  412. with Another Process"> and L<perlipc/"Bidirectional Communication with
  413. Yourself">
  414. You may also use the IPC::Open3 module (part of the standard perl
  415. distribution), but be warned that it has a different order of
  416. arguments from IPC::Open2 (see L<IPC::Open3>).
  417. =head2 Why can't I get the output of a command with system()?
  418. You're confusing the purpose of system() and backticks (``). system()
  419. runs a command and returns exit status information (as a 16 bit value:
  420. the low 7 bits are the signal the process died from, if any, and
  421. the high 8 bits are the actual exit value). Backticks (``) run a
  422. command and return what it sent to STDOUT.
  423. $exit_status = system("mail-users");
  424. $output_string = `ls`;
  425. =head2 How can I capture STDERR from an external command?
  426. There are three basic ways of running external commands:
  427. system $cmd; # using system()
  428. $output = `$cmd`; # using backticks (``)
  429. open (PIPE, "cmd |"); # using open()
  430. With system(), both STDOUT and STDERR will go the same place as the
  431. script's versions of these, unless the command redirects them.
  432. Backticks and open() read B<only> the STDOUT of your command.
  433. With any of these, you can change file descriptors before the call:
  434. open(STDOUT, ">logfile");
  435. system("ls");
  436. or you can use Bourne shell file-descriptor redirection:
  437. $output = `$cmd 2>some_file`;
  438. open (PIPE, "cmd 2>some_file |");
  439. You can also use file-descriptor redirection to make STDERR a
  440. duplicate of STDOUT:
  441. $output = `$cmd 2>&1`;
  442. open (PIPE, "cmd 2>&1 |");
  443. Note that you I<cannot> simply open STDERR to be a dup of STDOUT
  444. in your Perl program and avoid calling the shell to do the redirection.
  445. This doesn't work:
  446. open(STDERR, ">&STDOUT");
  447. $alloutput = `cmd args`; # stderr still escapes
  448. This fails because the open() makes STDERR go to where STDOUT was
  449. going at the time of the open(). The backticks then make STDOUT go to
  450. a string, but don't change STDERR (which still goes to the old
  451. STDOUT).
  452. Note that you I<must> use Bourne shell (sh(1)) redirection syntax in
  453. backticks, not csh(1)! Details on why Perl's system() and backtick
  454. and pipe opens all use the Bourne shell are in
  455. http://www.perl.com/CPAN/doc/FMTEYEWTK/versus/csh.whynot .
  456. To capture a command's STDERR and STDOUT together:
  457. $output = `cmd 2>&1`; # either with backticks
  458. $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
  459. while (<PH>) { } # plus a read
  460. To capture a command's STDOUT but discard its STDERR:
  461. $output = `cmd 2>/dev/null`; # either with backticks
  462. $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
  463. while (<PH>) { } # plus a read
  464. To capture a command's STDERR but discard its STDOUT:
  465. $output = `cmd 2>&1 1>/dev/null`; # either with backticks
  466. $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
  467. while (<PH>) { } # plus a read
  468. To exchange a command's STDOUT and STDERR in order to capture the STDERR
  469. but leave its STDOUT to come out our old STDERR:
  470. $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
  471. $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
  472. while (<PH>) { } # plus a read
  473. To read both a command's STDOUT and its STDERR separately, it's easiest
  474. and safest to redirect them separately to files, and then read from those
  475. files when the program is done:
  476. system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
  477. Ordering is important in all these examples. That's because the shell
  478. processes file descriptor redirections in strictly left to right order.
  479. system("prog args 1>tmpfile 2>&1");
  480. system("prog args 2>&1 1>tmpfile");
  481. The first command sends both standard out and standard error to the
  482. temporary file. The second command sends only the old standard output
  483. there, and the old standard error shows up on the old standard out.
  484. =head2 Why doesn't open() return an error when a pipe open fails?
  485. Because the pipe open takes place in two steps: first Perl calls
  486. fork() to start a new process, then this new process calls exec() to
  487. run the program you really wanted to open. The first step reports
  488. success or failure to your process, so open() can only tell you
  489. whether the fork() succeeded or not.
  490. To find out if the exec() step succeeded, you have to catch SIGCHLD
  491. and wait() to get the exit status. You should also catch SIGPIPE if
  492. you're writing to the child--you may not have found out the exec()
  493. failed by the time you write. This is documented in L<perlipc>.
  494. In some cases, even this won't work. If the second argument to a
  495. piped open() contains shell metacharacters, perl fork()s, then exec()s
  496. a shell to decode the metacharacters and eventually run the desired
  497. program. Now when you call wait(), you only learn whether or not the
  498. I<shell> could be successfully started. Best to avoid shell
  499. metacharacters.
  500. On systems that follow the spawn() paradigm, open() I<might> do what
  501. you expect--unless perl uses a shell to start your command. In this
  502. case the fork()/exec() description still applies.
  503. =head2 What's wrong with using backticks in a void context?
  504. Strictly speaking, nothing. Stylistically speaking, it's not a good
  505. way to write maintainable code because backticks have a (potentially
  506. humungous) return value, and you're ignoring it. It's may also not be very
  507. efficient, because you have to read in all the lines of output, allocate
  508. memory for them, and then throw it away. Too often people are lulled
  509. to writing:
  510. `cp file file.bak`;
  511. And now they think "Hey, I'll just always use backticks to run programs."
  512. Bad idea: backticks are for capturing a program's output; the system()
  513. function is for running programs.
  514. Consider this line:
  515. `cat /etc/termcap`;
  516. You haven't assigned the output anywhere, so it just wastes memory
  517. (for a little while). Plus you forgot to check C<$?> to see whether
  518. the program even ran correctly. Even if you wrote
  519. print `cat /etc/termcap`;
  520. In most cases, this could and probably should be written as
  521. system("cat /etc/termcap") == 0
  522. or die "cat program failed!";
  523. Which will get the output quickly (as its generated, instead of only
  524. at the end) and also check the return value.
  525. system() also provides direct control over whether shell wildcard
  526. processing may take place, whereas backticks do not.
  527. =head2 How can I call backticks without shell processing?
  528. This is a bit tricky. Instead of writing
  529. @ok = `grep @opts '$search_string' @filenames`;
  530. You have to do this:
  531. my @ok = ();
  532. if (open(GREP, "-|")) {
  533. while (<GREP>) {
  534. chomp;
  535. push(@ok, $_);
  536. }
  537. close GREP;
  538. } else {
  539. exec 'grep', @opts, $search_string, @filenames;
  540. }
  541. Just as with system(), no shell escapes happen when you exec() a list.
  542. There are more examples of this L<perlipc/"Safe Pipe Opens">.
  543. =head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
  544. Because some stdio's set error and eof flags that need clearing. The
  545. POSIX module defines clearerr() that you can use. That is the
  546. technically correct way to do it. Here are some less reliable
  547. workarounds:
  548. =over 4
  549. =item 1
  550. Try keeping around the seekpointer and go there, like this:
  551. $where = tell(LOG);
  552. seek(LOG, $where, 0);
  553. =item 2
  554. If that doesn't work, try seeking to a different part of the file and
  555. then back.
  556. =item 3
  557. If that doesn't work, try seeking to a different part of
  558. the file, reading something, and then seeking back.
  559. =item 4
  560. If that doesn't work, give up on your stdio package and use sysread.
  561. =back
  562. =head2 How can I convert my shell script to perl?
  563. Learn Perl and rewrite it. Seriously, there's no simple converter.
  564. Things that are awkward to do in the shell are easy to do in Perl, and
  565. this very awkwardness is what would make a shell->perl converter
  566. nigh-on impossible to write. By rewriting it, you'll think about what
  567. you're really trying to do, and hopefully will escape the shell's
  568. pipeline datastream paradigm, which while convenient for some matters,
  569. causes many inefficiencies.
  570. =head2 Can I use perl to run a telnet or ftp session?
  571. Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
  572. CPAN). http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar
  573. will also help for emulating the telnet protocol, but Net::Telnet is
  574. quite probably easier to use..
  575. If all you want to do is pretend to be telnet but don't need
  576. the initial telnet handshaking, then the standard dual-process
  577. approach will suffice:
  578. use IO::Socket; # new in 5.004
  579. $handle = IO::Socket::INET->new('www.perl.com:80')
  580. || die "can't connect to port 80 on www.perl.com: $!";
  581. $handle->autoflush(1);
  582. if (fork()) { # XXX: undef means failure
  583. select($handle);
  584. print while <STDIN>; # everything from stdin to socket
  585. } else {
  586. print while <$handle>; # everything from socket to stdout
  587. }
  588. close $handle;
  589. exit;
  590. =head2 How can I write expect in Perl?
  591. Once upon a time, there was a library called chat2.pl (part of the
  592. standard perl distribution), which never really got finished. If you
  593. find it somewhere, I<don't use it>. These days, your best bet is to
  594. look at the Expect module available from CPAN, which also requires two
  595. other modules from CPAN, IO::Pty and IO::Stty.
  596. =head2 Is there a way to hide perl's command line from programs such as "ps"?
  597. First of all note that if you're doing this for security reasons (to
  598. avoid people seeing passwords, for example) then you should rewrite
  599. your program so that critical information is never given as an
  600. argument. Hiding the arguments won't make your program completely
  601. secure.
  602. To actually alter the visible command line, you can assign to the
  603. variable $0 as documented in L<perlvar>. This won't work on all
  604. operating systems, though. Daemon programs like sendmail place their
  605. state there, as in:
  606. $0 = "orcus [accepting connections]";
  607. =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?
  608. =over 4
  609. =item Unix
  610. In the strictest sense, it can't be done -- the script executes as a
  611. different process from the shell it was started from. Changes to a
  612. process are not reflected in its parent, only in its own children
  613. created after the change. There is shell magic that may allow you to
  614. fake it by eval()ing the script's output in your shell; check out the
  615. comp.unix.questions FAQ for details.
  616. =back
  617. =head2 How do I close a process's filehandle without waiting for it to complete?
  618. Assuming your system supports such things, just send an appropriate signal
  619. to the process (see L<perlfunc/"kill">. It's common to first send a TERM
  620. signal, wait a little bit, and then send a KILL signal to finish it off.
  621. =head2 How do I fork a daemon process?
  622. If by daemon process you mean one that's detached (disassociated from
  623. its tty), then the following process is reported to work on most
  624. Unixish systems. Non-Unix users should check their Your_OS::Process
  625. module for other solutions.
  626. =over 4
  627. =item *
  628. Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty(4)>
  629. for details. Or better yet, you can just use the POSIX::setsid()
  630. function, so you don't have to worry about process groups.
  631. =item *
  632. Change directory to /
  633. =item *
  634. Reopen STDIN, STDOUT, and STDERR so they're not connected to the old
  635. tty.
  636. =item *
  637. Background yourself like this:
  638. fork && exit;
  639. =back
  640. The Proc::Daemon module, available from CPAN, provides a function to
  641. perform these actions for you.
  642. =head2 How do I make my program run with sh and csh?
  643. See the F<eg/nih> script (part of the perl source distribution).
  644. =head2 How do I find out if I'm running interactively or not?
  645. Good question. Sometimes C<-t STDIN> and C<-t STDOUT> can give clues,
  646. sometimes not.
  647. if (-t STDIN && -t STDOUT) {
  648. print "Now what? ";
  649. }
  650. On POSIX systems, you can test whether your own process group matches
  651. the current process group of your controlling terminal as follows:
  652. use POSIX qw/getpgrp tcgetpgrp/;
  653. open(TTY, "/dev/tty") or die $!;
  654. $tpgrp = tcgetpgrp(fileno(*TTY));
  655. $pgrp = getpgrp();
  656. if ($tpgrp == $pgrp) {
  657. print "foreground\n";
  658. } else {
  659. print "background\n";
  660. }
  661. =head2 How do I timeout a slow event?
  662. Use the alarm() function, probably in conjunction with a signal
  663. handler, as documented L<perlipc/"Signals"> and chapter 6 of the
  664. Camel. You may instead use the more flexible Sys::AlarmCall module
  665. available from CPAN.
  666. =head2 How do I set CPU limits?
  667. Use the BSD::Resource module from CPAN.
  668. =head2 How do I avoid zombies on a Unix system?
  669. Use the reaper code from L<perlipc/"Signals"> to call wait() when a
  670. SIGCHLD is received, or else use the double-fork technique described
  671. in L<perlfunc/fork>.
  672. =head2 How do I use an SQL database?
  673. There are a number of excellent interfaces to SQL databases. See the
  674. DBD::* modules available from
  675. http://www.perl.com/CPAN/modules/dbperl/DBD .
  676. A lot of information on this can be found at
  677. http://www.hermetica.com/technologia/perl/DBI/index.html .
  678. =head2 How do I make a system() exit on control-C?
  679. You can't. You need to imitate the system() call (see L<perlipc> for
  680. sample code) and then have a signal handler for the INT signal that
  681. passes the signal on to the subprocess. Or you can check for it:
  682. $rc = system($cmd);
  683. if ($rc & 127) { die "signal death" }
  684. =head2 How do I open a file without blocking?
  685. If you're lucky enough to be using a system that supports
  686. non-blocking reads (most Unixish systems do), you need only to use the
  687. O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with
  688. sysopen():
  689. use Fcntl;
  690. sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
  691. or die "can't open /tmp/somefile: $!":
  692. =head2 How do I install a CPAN module?
  693. The easiest way is to have the CPAN module do it for you. This module
  694. comes with perl version 5.004 and later. To manually install the CPAN
  695. module, or any well-behaved CPAN module for that matter, follow these
  696. steps:
  697. =over 4
  698. =item 1
  699. Unpack the source into a temporary area.
  700. =item 2
  701. perl Makefile.PL
  702. =item 3
  703. make
  704. =item 4
  705. make test
  706. =item 5
  707. make install
  708. =back
  709. If your version of perl is compiled without dynamic loading, then you
  710. just need to replace step 3 (B<make>) with B<make perl> and you will
  711. get a new F<perl> binary with your extension linked in.
  712. See L<ExtUtils::MakeMaker> for more details on building extensions.
  713. See also the next question.
  714. =head2 What's the difference between require and use?
  715. Perl offers several different ways to include code from one file into
  716. another. Here are the deltas between the various inclusion constructs:
  717. 1) do $file is like eval `cat $file`, except the former:
  718. 1.1: searches @INC and updates %INC.
  719. 1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
  720. 2) require $file is like do $file, except the former:
  721. 2.1: checks for redundant loading, skipping already loaded files.
  722. 2.2: raises an exception on failure to find, compile, or execute $file.
  723. 3) require Module is like require "Module.pm", except the former:
  724. 3.1: translates each "::" into your system's directory separator.
  725. 3.2: primes the parser to disambiguate class Module as an indirect object.
  726. 4) use Module is like require Module, except the former:
  727. 4.1: loads the module at compile time, not run-time.
  728. 4.2: imports symbols and semantics from that package to the current one.
  729. In general, you usually want C<use> and a proper Perl module.
  730. =head2 How do I keep my own module/library directory?
  731. When you build modules, use the PREFIX option when generating
  732. Makefiles:
  733. perl Makefile.PL PREFIX=/u/mydir/perl
  734. then either set the PERL5LIB environment variable before you run
  735. scripts that use the modules/libraries (see L<perlrun>) or say
  736. use lib '/u/mydir/perl';
  737. This is almost the same as:
  738. BEGIN {
  739. unshift(@INC, '/u/mydir/perl');
  740. }
  741. except that the lib module checks for machine-dependent subdirectories.
  742. See Perl's L<lib> for more information.
  743. =head2 How do I add the directory my program lives in to the module/library search path?
  744. use FindBin;
  745. use lib "$FindBin::Bin";
  746. use your_own_modules;
  747. =head2 How do I add a directory to my include path at runtime?
  748. Here are the suggested ways of modifying your include path:
  749. the PERLLIB environment variable
  750. the PERL5LIB environment variable
  751. the perl -Idir command line flag
  752. the use lib pragma, as in
  753. use lib "$ENV{HOME}/myown_perllib";
  754. The latter is particularly useful because it knows about machine
  755. dependent architectures. The lib.pm pragmatic module was first
  756. included with the 5.002 release of Perl.
  757. =head2 What is socket.ph and where do I get it?
  758. It's a perl4-style file defining values for system networking
  759. constants. Sometimes it is built using h2ph when Perl is installed,
  760. but other times it is not. Modern programs C<use Socket;> instead.
  761. =head1 AUTHOR AND COPYRIGHT
  762. Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
  763. All rights reserved.
  764. When included as part of the Standard Version of Perl, or as part of
  765. its complete documentation whether printed or otherwise, this work
  766. may be distributed only under the terms of Perl's Artistic Licence.
  767. Any distribution of this file or derivatives thereof I<outside>
  768. of that package require that special arrangements be made with
  769. copyright holder.
  770. Irrespective of its distribution, all code examples in this file
  771. are hereby placed into the public domain. You are permitted and
  772. encouraged to use this code in your own programs for fun
  773. or for profit as you see fit. A simple comment in the code giving
  774. credit would be courteous but is not required.