Leaked source code of windows server 2003
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.

1103 lines
38 KiB

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