Полезная информация

Programming Perl

Programming PerlSearch this book
Previous: 3.2.36 expChapter 3
Functions
Next: 3.2.38 fileno
 

3.2.37 fcntl

fcntl FILEHANDLE, FUNCTION, SCALAR

This function calls UNIX's fcntl(2) function. (fcntl stands for "file control".) You'll probably have to say:

use Fcntl;

first to get the correct function definitions. SCALAR will be read and/or written depending on the FUNCTION - a pointer to the string value of SCALAR will be passed as the third argument of the actual fcntl call. (If SCALAR has no string value but does have a numeric value, that value will be passed directly rather than a pointer to the string value.)

The return value of fcntl (and ioctl) is as follows:

System call returnsPerl returns
-1undefined value
0string "0 but true"
anything elsethat number

Thus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system:

$retval = fcntl(...) or $retval = -1;
printf "System returned %d\n", $retval;

Here, even the string "0 but true" prints as 0, thanks to the %d format.

For example, since Perl always sets the close-on-exec flag for file descriptors above 2, if you wanted to pass file descriptor 3 to a subprocess, you might want to clear the flag like this:

use Fcntl;
open TTY,"+>/dev/tty" or die "Can't open /dev/tty: $!\n";
fileno TTY == 3 or die "Internal error: fd mixup";
fcntl TTY, &F_SETFL, 0
    or die "Can't clear the close-on-exec flag: $!\n";

fcntl will produce a fatal error if used on a machine that doesn't implement fcntl(2). On machines that do implement it, you can do such things as modify the close-on-exec flags, modify the non-blocking I/O flags, emulate the lockf(3) function, and arrange to receive the SIGIO signal when I/O is pending. You might even have record-locking facilities.


Previous: 3.2.36 expProgramming PerlNext: 3.2.38 fileno
3.2.36 expBook Index3.2.38 fileno