ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
  |_ Core Documentation
    |_ perl
    |_ perlintro
    |_ perltoc
    |_ perlreftut
    |_ perldsc
    |_ perllol
    |_ perlrequick
    |_ perlretut
    |_ perlboot
    |_ perltoot
    |_ perltooc
    |_ perlbot
    |_ perlstyle
    |_ perlcheat
    |_ perltrap
    |_ perldebtut
    |_ perlfaq
    |_ perlfaq1
    |_ perlfaq2
    |_ perlfaq3
    |_ perlfaq4
    |_ perlfaq5
    |_ perlfaq6
    |_ perlfaq7
    |_ perlfaq8
    |_ perlfaq9
    |_ perlsyn
    |_ perldata
    |_ perlop
    |_ perlsub
    |_ perlfunc
    |_ perlopentut
    |_ perlpacktut
    |_ perlpod
    |_ perlpodspec
    |_ perlrun
    |_ perldiag
    |_ perllexwarn
    |_ perldebug
    |_ perlvar
    |_ perlre
    |_ perlrebackslash
    |_ perlrecharclass
    |_ perlreref
    |_ perlref
    |_ perlform
    |_ perlobj
    |_ perltie
    |_ perldbmfilter
    |_ perlipc
    |_ perlfork
    |_ perlnumber
    |_ perlthrtut
    |_ perlothrtut
    |_ perlport
    |_ perllocale
    |_ perluniintro
    |_ perlunicode
    |_ perlunifaq
    |_ perlunitut
    |_ perlebcdic
    |_ perlsec
    |_ perlmod
    |_ perlmodlib
    |_ perlmodstyle
    |_ perlmodinstall
    |_ perlnewmod
    |_ perlutil
    |_ perlcompile
    |_ perlfilter
    |_ perlglossary
    |_ perlembed
    |_ perldebguts
    |_ perlxstut
    |_ perlxs
    |_ perlclib
    |_ perlguts
    |_ perlcall
    |_ perlreguts
    |_ perlapi
    |_ perlintern
    |_ perliol
    |_ perlapio
    |_ perlhack
    |_ perlbook
    |_ perlcommunity
    |_ perltodo
    |_ perldoc
    |_ perlhist
    |_ perldelta
    |_ perl588delta
    |_ perl587delta
    |_ perl586delta
    |_ perl585delta
    |_ perl584delta
    |_ perl583delta
    |_ perl582delta
    |_ perl581delta
    |_ perl58delta
    |_ perl573delta
    |_ perl572delta
    |_ perl571delta
    |_ perl570delta
    |_ perl561delta
    |_ perl56delta
    |_ perl5005delta
    |_ perl5004delta
    |_ perlartistic
    |_ perlgpl
    |_ perlcn
    |_ perljp
    |_ perlko
    |_ perltw
    |_ perlaix
    |_ perlamiga
    |_ perlapollo
    |_ perlbeos
    |_ perlbs2000
    |_ perlce
    |_ perlcygwin
    |_ perldgux
    |_ perldos
    |_ perlepoc
    |_ perlfreebsd
    |_ perlhpux
    |_ perlhurd
    |_ perlirix
    |_ perllinux
    |_ perlmachten
    |_ perlmacos
    |_ perlmacosx
    |_ perlmint
    |_ perlmpeix
    |_ perlnetware
    |_ perlopenbsd
    |_ perlos2
    |_ perlos390
    |_ perlos400
    |_ perlplan9
    |_ perlqnx
    |_ perlriscos
    |_ perlsolaris
    |_ perltru64
    |_ perluts
    |_ perlvmesa
    |_ perlvms
    |_ perlvos
    |_ perlwin32




Advertise Jobs

< perlfaq7 perlfaq9 >


perlfaq8 - System Interaction


NAME

perlfaq8 - System Interaction ($Revision: 10183 $)


DESCRIPTION

This section of the Perl FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation.

Read the FAQs and documentation specific to the port of perl to your operating system (eg, the perlvms manpage, the perlplan9 manpage, ...). These should contain more detailed information on the vagaries of your perl.

How do I find out which operating system I'm running under?

The $^O variable ($OSNAME if you use English) contains an indication of the name of the operating system (not its release number) that your perl binary was built for.

How come exec() doesn't return?

Because that's what it does: it replaces your currently running program with a different one. If you want to keep going (as is probably the case if you're asking this question) use system() instead.

How do I do fancy stuff with the keyboard/screen/mouse?

How you access/control keyboards, screens, and pointing devices ("mice") is system-dependent. Try the following modules:

Keyboard
        Term::Cap               Standard perl distribution
        Term::ReadKey           CPAN
        Term::ReadLine::Gnu     CPAN
        Term::ReadLine::Perl    CPAN
        Term::Screen            CPAN
Screen
        Term::Cap               Standard perl distribution
        Curses                  CPAN
        Term::ANSIColor         CPAN
Mouse
        Tk                      CPAN

Some of these specific cases are shown as examples in other answers in this section of the perlfaq.

How do I print something out in color?

In general, you don't, because you don't know whether the recipient has a color-aware display device. If you know that they have an ANSI terminal that understands color, you can use the Term::ANSIColor module from CPAN:

        use Term::ANSIColor;
        print color("red"), "Stop!\n", color("reset");
        print color("green"), "Go!\n", color("reset");

Or like this:

        use Term::ANSIColor qw(:constants);
        print RED, "Stop!\n", RESET;
        print GREEN, "Go!\n", RESET;

How do I read just one key without waiting for a return key?

Controlling input buffering is a remarkably system-dependent matter. On many systems, you can just use the stty command as shown in getc in the perlfunc manpage, but as you see, that's already getting you into portability snags.

        open(TTY, "+</dev/tty") or die "no tty: $!";
        system "stty  cbreak </dev/tty >/dev/tty 2>&1";
        $key = getc(TTY);               # perhaps this works
        # OR ELSE
        sysread(TTY, $key, 1);  # probably this does
        system "stty -cbreak </dev/tty >/dev/tty 2>&1";

The Term::ReadKey module from CPAN offers an easy-to-use interface that should be more efficient than shelling out to stty for each key. It even includes limited support for Windows.

        use Term::ReadKey;
        ReadMode('cbreak');
        $key = ReadKey(0);
        ReadMode('normal');

However, using the code requires that you have a working C compiler and can use it to build and install a CPAN module. Here's a solution using the standard POSIX module, which is already on your systems (assuming your system supports POSIX).

        use HotKey;
        $key = readkey();

And here's the HotKey module, which hides the somewhat mystifying calls to manipulate the POSIX termios structures.

        # HotKey.pm
        package HotKey;
        @ISA = qw(Exporter);
        @EXPORT = qw(cbreak cooked readkey);
        use strict;
        use POSIX qw(:termios_h);
        my ($term, $oterm, $echo, $noecho, $fd_stdin);
        $fd_stdin = fileno(STDIN);
        $term     = POSIX::Termios->new();
        $term->getattr($fd_stdin);
        $oterm     = $term->getlflag();
        $echo     = ECHO | ECHOK | ICANON;
        $noecho   = $oterm & ~$echo;
        sub cbreak {
                $term->setlflag($noecho);  # ok, so i don't want echo either
                $term->setcc(VTIME, 1);
                $term->setattr($fd_stdin, TCSANOW);
        }
        sub cooked {
                $term->setlflag($oterm);
                $term->setcc(VTIME, 0);
                $term->setattr($fd_stdin, TCSANOW);
        }
        sub readkey {
                my $key = '';
                cbreak();
                sysread(STDIN, $key, 1);
                cooked();
                return $key;
        }
        END { cooked() }
        1;

How do I check whether input is ready on the keyboard?

The easiest way to do this is to read a key in nonblocking mode with the Term::ReadKey module from CPAN, passing it an argument of -1 to indicate not to block:

        use Term::ReadKey;
        ReadMode('cbreak');
        if (defined ($char = ReadKey(-1)) ) {
                # input was waiting and it was $char
        } else {
                # no input was waiting
        }
        ReadMode('normal');                  # restore normal tty settings

How do I clear the screen?

If you only have do so infrequently, use system:

        system("clear");

If you have to do this a lot, save the clear string so you can print it 100 times without calling a program 100 times:

        $clear_string = `clear`;
        print $clear_string;

If you're planning on doing other screen manipulations, like cursor positions, etc, you might wish to use Term::Cap module:

        use Term::Cap;
        $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
        $clear_string = $terminal->Tputs('cl');

How do I get the screen size?

If you have Term::ReadKey module installed from CPAN, you can use it to fetch the width and height in characters and in pixels:

        use Term::ReadKey;
        ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();

This is more portable than the raw ioctl, but not as illustrative:

        require 'sys/ioctl.ph';
        die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
        open(TTY, "+</dev/tty")                     or die "No tty: $!";
        unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
                die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
        }
        ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
        print "(row,col) = ($row,$col)";
        print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
        print "\n";

How do I ask the user for a password?

(This question has nothing to do with the web. See a different FAQ for that.)

There's an example of this in crypt in the perlfunc manpage). First, you put the terminal into "no echo" mode, then just read the password normally. You may do this with an old-style ioctl() function, POSIX terminal control (see the POSIX manpage or its documentation the Camel Book), or a call to the stty program, with varying degrees of portability.

You can also do this for most systems using the Term::ReadKey module from CPAN, which is easier to use and in theory more portable.

        use Term::ReadKey;
        ReadMode('noecho');
        $password = ReadLine(0);

How do I read and write the serial port?

This depends on which operating system your program is running on. In the case of Unix, the serial ports will be accessible through files in /dev; on other systems, device names will doubtless differ. Several problem areas common to all device interaction are the following:

lockfiles

Your system may use lockfiles to control multiple access. Make sure you follow the correct protocol. Unpredictable behavior can result from multiple processes reading from one device.

open mode

If you expect to use both read and write operations on the device, you'll have to open it for update (see open in the perlfunc manpage for details). You may wish to open it without running the risk of blocking by using sysopen() and O_RDWR|O_NDELAY|O_NOCTTY from the Fcntl module (part of the standard perl distribution). See sysopen in the perlfunc manpage for more on this approach.

end of line

Some devices will be expecting a "\r" at the end of each line rather than a "\n". In some ports of perl, "\r" and "\n" are different from their usual (Unix) ASCII values of "\012" and "\015". You may have to give the numeric values you want directly, using octal ("\015"), hex ("0x0D"), or as a control-character specification ("\cM").

        print DEV "atv1\012";   # wrong, for some devices
        print DEV "atv1\015";   # right, for some devices

Even though with normal text files a "\n" will do the trick, there is still no unified scheme for terminating a line that is portable between Unix, DOS/Win, and Macintosh, except to terminate ALL line ends with "\015\012", and strip what you don't need from the output. This applies especially to socket I/O and autoflushing, discussed next.

flushing output

If you expect characters to get to your device when you print() them, you'll want to autoflush that filehandle. You can use select() and the $| variable to control autoflushing (see $| in the perlvar manpage and select in the perlfunc manpage, or the perlfaq5 manpage, "How do I flush/unbuffer an output filehandle? Why must I do this?"):

        $oldh = select(DEV);
        $| = 1;
        select($oldh);

You'll also see code that does this without a temporary variable, as in

        select((select(DEV), $| = 1)[0]);

Or if you don't mind pulling in a few thousand lines of code just because you're afraid of a little $| variable:

        use IO::Handle;
        DEV->autoflush(1);

As mentioned in the previous item, this still doesn't work when using socket I/O between Unix and Macintosh. You'll need to hard code your line terminators, in that case.

non-blocking input

If you are doing a blocking read() or sysread(), you'll have to arrange for an alarm handler to provide a timeout (see alarm in the perlfunc manpage). If you have a non-blocking open, you'll likely have a non-blocking read, which means you may have to use a 4-arg select() to determine whether I/O is ready on that device (see select in the perlfunc manpage.

While trying to read from his caller-id box, the notorious Jamie Zawinski <jwz@netscape.com>, after much gnashing of teeth and fighting with sysread, sysopen, POSIX's tcgetattr business, and various other functions that go bump in the night, finally came up with this:

        sub open_modem {
                use IPC::Open2;
                my $stty = `/bin/stty -g`;
                open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
                # starting cu hoses /dev/tty's stty settings, even when it has
                # been opened on a pipe...
                system("/bin/stty $stty");
                $_ = <MODEM_IN>;
                chomp;
                if ( !m/^Connected/ ) {
                        print STDERR "$0: cu printed `$_' instead of `Connected'\n";
                }
        }

How do I decode encrypted password files?

You spend lots and lots of money on dedicated hardware, but this is bound to get you talked about.

Seriously, you can't if they are Unix password files--the Unix password system employs one-way encryption. It's more like hashing than encryption. The best you can do is check whether something else hashes to the same string. You can't turn a hash back into the original string. Programs like Crack can forcibly (and intelligently) try to guess passwords, but don't (can't) guarantee quick success.

If you're worried about users selecting bad passwords, you should proactively check when they try to change their password (by modifying passwd(1), for example).

How do I start a process in the background?

Several modules can start other processes that do not block your Perl program. You can use IPC::Open3, Parallel::Jobs, IPC::Run, and some of the POE modules. See CPAN for more details.

You could also use

        system("cmd &")

or you could use fork as documented in fork in the perlfunc manpage, with further examples in the perlipc manpage. Some things to be aware of, if you're on a Unix-like system:

STDIN, STDOUT, and STDERR are shared

Both the main process and the backgrounded one (the "child" process) share the same STDIN, STDOUT and STDERR filehandles. If both try to access them at once, strange things can happen. You may want to close or reopen these for the child. You can get around this with opening a pipe (see open in the perlfunc manpage) but on some systems this means that the child process cannot outlive the parent.

Signals

You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too. SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is sent when you write to a filehandle whose child process has closed (an untrapped SIGPIPE can cause your program to silently die). This is not an issue with system("cmd&").

Zombies

You have to be prepared to "reap" the child process when it finishes.

        $SIG{CHLD} = sub { wait };
        $SIG{CHLD} = 'IGNORE';

You can also use a double fork. You immediately wait() for your first child, and the init daemon will wait() for your grandchild once it exits.

        unless ($pid = fork) {
            unless (fork) {
                exec "what you really wanna do";
                die "exec failed!";
            }
            exit 0;
        }
        waitpid($pid, 0);

See Signals in the perlipc manpage for other examples of code to do this. Zombies are not an issue with system("prog &").

How do I trap control characters/signals?

You don't actually "trap" a control character. Instead, that character generates a signal which is sent to your terminal's currently foregrounded process group, which you then trap in your process. Signals are documented in Signals in the perlipc manpage and the section on "Signals" in the Camel.

You can set the values of the %SIG hash to be the functions you want to handle the signal. After perl catches the signal, it looks in %SIG for a key with the same name as the signal, then calls the subroutine value for that key.

        # as an anonymous subroutine
        $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
        # or a reference to a function
        $SIG{INT} = \&ouch;
        # or the name of the function as a string
        $SIG{INT} = "ouch";

Perl versions before 5.8 had in its C source code signal handlers which would catch the signal and possibly run a Perl function that you had set in %SIG. This violated the rules of signal handling at that level causing perl to dump core. Since version 5.8.0, perl looks at %SIG *after* the signal has been caught, rather than while it is being caught. Previous versions of this answer were incorrect.

How do I modify the shadow password file on a Unix system?

If perl was installed correctly and your shadow library was written properly, the getpw*() functions described in the perlfunc manpage should in theory provide (read-only) access to entries in the shadow password file. To change the file, make a new shadow password file (the format varies from system to system--see passwd for specifics) and use pwd_mkdb(8) to install it (see pwd_mkdb for more details).

How do I set the time and date?

Assuming you're running under sufficient permissions, you should be able to set the system-wide date and time by running the date(1) program. (There is no way to set the time and date on a per-process basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT; the VMS equivalent is set time.

However, if all you want to do is change your time zone, you can probably get away with setting an environment variable:

        $ENV{TZ} = "MST7MDT";              # unixish
        $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
        system "trn comp.lang.perl.misc";

How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in the perlfunc manpage. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).

How can I measure time under a second?

(contributed by brian d foy)

The Time::HiRes module (part of the standard distribution as of Perl 5.8) measures time with the gettimeofday() system call, which returns the time in microseconds since the epoch. If you can't install Time::HiRes for older Perls and you are on a Unixish system, you may be able to call gettimeofday(2) directly. See syscall in the perlfunc manpage.

How can I do an atexit() or setjmp()/longjmp()? (Exception handling)

Release 5 of Perl added the END block, which can be used to simulate atexit(). Each package's END block is called when the program or thread ends (see the perlmod manpage manpage for more details).

For example, you can use this to make sure your filter program managed to finish its output without filling up the disk:

        END {
                close(STDOUT) || die "stdout close failed: $!";
        }

The END block isn't called when untrapped signals kill the program, though, so if you use END blocks you should also use

        use sigtrap qw(die normal-signals);

Perl's exception-handling mechanism is its eval() operator. You can use eval() as setjmp and die() as longjmp. For details of this, see the section on signals, especially the time-out handler for a blocking flock() in Signals in the perlipc manpage or the section on "Signals" in the Camel Book.

If exception handling is all you're interested in, try the exceptions.pl library (part of the standard perl distribution).

If you want the atexit() syntax (and an rmexit() as well), try the AtExit module available from CPAN.

Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?

Some Sys-V based systems, notably Solaris 2.X, redefined some of the standard socket constants. Since these were constant across all architectures, they were often hardwired into perl code. The proper way to deal with this is to "use Socket" to get the correct values.

Note that even though SunOS and Solaris are binary compatible, these values are different. Go figure.

How can I call my system's unique C functions from Perl?

In most cases, you write an external module to do it--see the answer to "Where can I learn about linking C with Perl? [h2xs, xsubpp]". However, if the function is a system call, and your system supports syscall(), you can use the syscall function (documented in the perlfunc manpage).

Remember to check the modules that came with your distribution, and CPAN as well--someone may already have written a module to do it. On Windows, try Win32::API. On Macs, try Mac::Carbon. If no module has an interface to the C function, you can inline a bit of C in your Perl source with Inline::C.

Where do I get the include files to do ioctl() or syscall()?

Historically, these would be generated by the h2ph tool, part of the standard perl distribution. This program converts cpp(1) directives in C header files to files containing subroutine definitions, like &SYS_getitimer, which you can use as arguments to your functions. It doesn't work perfectly, but it usually gets most of the job done. Simple files like errno.h, syscall.h, and socket.h were fine, but the hard ones like ioctl.h nearly always need to hand-edited. Here's how to install the *.ph files:

        1.  become super-user
        2.  cd /usr/include
        3.  h2ph *.h */*.h

If your system supports dynamic loading, for reasons of portability and sanity you probably ought to use h2xs (also part of the standard perl distribution). This tool converts C header files to Perl extensions. See the perlxstut manpage for how to get started with h2xs.

If your system doesn't support dynamic loading, you still probably ought to use h2xs. See the perlxstut manpage and the ExtUtils::MakeMaker manpage for more information (in brief, just use make perl instead of a plain make to rebuild perl with a new static extension).

Why do setuid perl scripts complain about kernel problems?

Some operating systems have bugs in the kernel that make setuid scripts inherently insecure. Perl gives you a number of options (described in the perlsec manpage) to work around such systems.

How can I open a pipe both to and from a command?

The IPC::Open2 module (part of the standard perl distribution) is an easy-to-use approach that internally uses pipe(), fork(), and exec() to do the job. Make sure you read the deadlock warnings in its documentation, though (see the IPC::Open2 manpage). See Bidirectional Communication with Another Process in the perlipc manpage and Bidirectional Communication with Yourself in the perlipc manpage

You may also use the IPC::Open3 module (part of the standard perl distribution), but be warned that it has a different order of arguments from IPC::Open2 (see the IPC::Open3 manpage).

Why can't I get the output of a command with system()?

You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.

        $exit_status   = system("mail-users");
        $output_string = `ls`;

How can I capture STDERR from an external command?

There are three basic ways of running external commands:

        system $cmd;            # using system()
        $output = `$cmd`;               # using backticks (``)
        open (PIPE, "cmd |");   # using open()

With system(), both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR, unless the system() command redirects them. Backticks and open() read only the STDOUT of your command.

You can also use the open3() function from IPC::Open3. Benjamin Goldberg provides some sample code:

To capture a program's STDOUT, but discard its STDERR:

        use IPC::Open3;
        use File::Spec;
        use Symbol qw(gensym);
        open(NULL, ">", File::Spec->devnull);
        my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
        while( <PH> ) { }
        waitpid($pid, 0);

To capture a program's STDERR, but discard its STDOUT:

        use IPC::Open3;
        use File::Spec;
        use Symbol qw(gensym);
        open(NULL, ">", File::Spec->devnull);
        my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
        while( <PH> ) { }
        waitpid($pid, 0);

To capture a program's STDERR, and let its STDOUT go to our own STDERR:

        use IPC::Open3;
        use Symbol qw(gensym);
        my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
        while( <PH> ) { }
        waitpid($pid, 0);

To read both a command's STDOUT and its STDERR separately, you can redirect them to temp files, let the command run, then read the temp files:

        use IPC::Open3;
        use Symbol qw(gensym);
        use IO::File;
        local *CATCHOUT = IO::File->new_tmpfile;
        local *CATCHERR = IO::File->new_tmpfile;
        my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
        waitpid($pid, 0);
        seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
        while( <CATCHOUT> ) {}
        while( <CATCHERR> ) {}

But there's no real need for *both* to be tempfiles... the following should work just as well, without deadlocking:

        use IPC::Open3;
        use Symbol qw(gensym);
        use IO::File;
        local