--- name: POSIX runtime: pp source: src/native/POSIX/pp.rs --- ```{index} single: POSIX; Perl module (pp runtime) ``` # POSIX Native implementation of Perl's POSIX module Provides POSIX constants, math functions, system calls, and utilities. # Implemented Categories - **Constants**: errno, signals, wait status, fcntl/open/seek, file modes, float/integer limits, math constants, FP classification, stdio/stdlib, termios, unistd - **Math functions**: 1-arg (acos..trunc), 2-arg (copysign..remainder), special (frexp, modf, ldexp, fma, remquo, etc.) - **FP classification**: fpclassify, ilogb, isfinite, isinf, isnan, etc. - **Time functions**: asctime, mktime, clock, ctime, difftime, strftime, times, tzset, tzname - **System info**: uname, sysconf, pathconf, fpathconf - **String functions**: strtod, strtol, strtoul, strcoll, strerror, strstr - **File I/O**: open, mkfifo, access - **Process control**: _exit, abort, nice, pause, setgid, setuid, etc. - **FD operations**: close, dup, dup2, lseek, pipe, read, write, etc. - **Terminal**: ctermid, ttyname - **Locale**: setlocale, localeconv # Synopsis use POSIX qw(floor ceil strftime uname strtod); my $f = floor(3.7); # 3 my $c = ceil(3.2); # 4 my $str = strftime("%Y-%m-%d %H:%M:%S", localtime); my ($sysname, $nodename, $release, $version, $machine) = uname(); my ($num, $unparsed) = strtod("3.14foo"); # (3.14, 3) use POSIX ':signal_h'; sigaction(SIGTERM, POSIX::SigAction->new(sub { die "caught" })); # Functions **Math: 1-argument (NV -> NV)** ## floor Return the largest integer not greater than the argument. ```perl use POSIX 'floor'; my $f = floor(3.7); # 3 ``` ## ceil Return the smallest integer not less than the argument. ```perl use POSIX 'ceil'; my $c = ceil(3.2); # 4 ``` ## fmod Return the floating-point remainder of x/y. ```perl use POSIX 'fmod'; my $r = fmod(10.5, 3.0); # 1.5 ``` ## round Round to the nearest integer, halfway cases away from zero. ```perl use POSIX 'round'; my $r = round(2.5); # 3 ``` ## trunc Truncate toward zero (discard fractional part). ```perl use POSIX 'trunc'; my $t = trunc(-3.7); # -3 ``` ## acos / acosh / asin / asinh / atan / atanh Inverse trigonometric and hyperbolic functions. ## cbrt / cosh / sinh / tanh / tan Cube root and hyperbolic/trigonometric functions. ## exp2 / expm1 / log10 / log1p / log2 / logb Exponential and logarithmic functions. ## erf / erfc / lgamma / tgamma Error functions and gamma functions. ## j0 / j1 / jn / y0 / y1 / yn Bessel functions of the first and second kind. ## nearbyint / rint Round to nearest integer using current rounding mode. **Math: 2-argument (NV, NV -> NV)** ## copysign Return a value with the magnitude of x and the sign of y. ## fdim / fmax / fmin Positive difference, maximum, and minimum of two floats. ## hypot Return sqrt(x*x + y*y) without overflow. ## remainder / nextafter IEEE remainder and next representable float toward y. **Math: Special** ## frexp Split a float into normalized fraction and exponent. Returns (fraction, exponent). ```perl use POSIX 'frexp'; my ($frac, $exp) = frexp(8.0); # (0.5, 4) ``` ## modf Split a float into integer and fractional parts. Returns (fraction, integer). ```perl use POSIX 'modf'; my ($frac, $int) = modf(3.75); # (0.75, 3.0) ``` ## ldexp Multiply a float by 2 raised to an integer power: x * 2^exp. ```perl use POSIX 'ldexp'; my $v = ldexp(0.5, 4); # 8.0 ``` ## fma Fused multiply-add: x*y + z with a single rounding step. ## remquo Return the remainder and partial quotient of x/y. ## scalbn Scale a float by a power of the radix: x * FLT_RADIX^n. ## nan Return a quiet NaN with the given payload string. **FP Classification** ## fpclassify Classify a floating-point value (FP_NAN, FP_INFINITE, FP_ZERO, FP_SUBNORMAL, FP_NORMAL). ## ilogb Return the exponent of a float as a signed integer. ## isfinite / isinf / isnan / isnormal / signbit Floating-point classification predicates. Return 1 (true) or 0 (false). ## lrint / lround Round to nearest long integer (lrint uses current rounding mode, lround rounds halfway away from zero). **FP Rounding Mode** ## fegetround Get the current floating-point rounding direction. ## fesetround Set the floating-point rounding direction (FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZERO). **Time Functions** ## strftime Format a broken-down time according to a format string. ```perl use POSIX 'strftime'; my $str = strftime("%Y-%m-%d", localtime); ``` ## mktime Convert broken-down time to epoch seconds. ```perl use POSIX 'mktime'; my $epoch = mktime($sec, $min, $hour, $mday, $mon, $year); ``` ## asctime Convert broken-down time to a string in ctime(3) format. ## ctime Convert epoch seconds to a human-readable local time string. ## difftime Return the difference in seconds between two time values. ## clock Return the processor time consumed by the program in clock ticks. ## times Return process and child CPU times as (real, user, system, cuser, csystem). ## tzset Set timezone information from the TZ environment variable. ## tzname Return the standard and daylight-saving timezone names as a two-element list. **System Info** ## uname Return system identification as (sysname, nodename, release, version, machine). ```perl use POSIX 'uname'; my ($sys, $node, $rel, $ver, $mach) = uname(); ``` ## sysconf Get the value of a configurable system limit or option. ## pathconf / fpathconf Get the value of a configurable pathname/file-descriptor limit. **String Functions** ## strtod Convert a string to a double. Returns (value, unparsed_length). ```perl use POSIX 'strtod'; my ($val, $remaining) = strtod("3.14foo"); ``` ## strtol Convert a string to a long integer with the given base. Returns (value, unparsed_length). ```perl use POSIX 'strtol'; my ($val, $remaining) = strtol("0xFF", 16); ``` ## strtoul Convert a string to an unsigned long integer with the given base. ## strcoll Compare two strings according to the current locale. ## strerror Return the error message string for an errno value. ```perl use POSIX 'strerror'; print strerror(2); # "No such file or directory" ``` ## strstr Find the first occurrence of a substring. Returns the offset or -1. **File I/O** ## open Open a file using POSIX semantics (returns a raw file descriptor). ```perl use POSIX qw(open O_RDONLY); my $fd = POSIX::open("/etc/passwd", O_RDONLY); ``` ## mkfifo Create a FIFO (named pipe) with the specified permissions. ## access Check file accessibility (R_OK, W_OK, X_OK, F_OK). Returns "0 but true" on success. **Process Control** ## _exit Terminate the process immediately without cleanup (unlike exit). ## abort Abort the process, generating a core dump. ## nice Change the process scheduling priority by the given increment. ## pause Suspend the process until a signal is received. ## setgid / setuid / setpgid / setsid Set group ID, user ID, process group ID, or create a new session. ## sleep Suspend execution for the specified number of seconds (C-level, not Perl's sleep). ## getcwd Return the current working directory as a string. ## lchown Change ownership of a symlink (does not follow the link). **Wait Status Macros** ## WEXITSTATUS / WIFEXITED / WIFSIGNALED / WIFSTOPPED / WSTOPSIG / WTERMSIG Inspect the status value returned by waitpid(). Standard POSIX wait macros. ```perl use POSIX ':sys_wait_h'; if (WIFEXITED($status)) { print "exit code: ", WEXITSTATUS($status); } ``` **FD Operations** ## close Close a file descriptor. Returns 0 on success, -1 on failure. ## dup / dup2 Duplicate a file descriptor. dup2 duplicates to a specific target FD. ## lseek Reposition the file offset of an open file descriptor. ## pipe Create a pair of connected file descriptors. Returns (read_fd, write_fd). ## read Read bytes from a file descriptor into a buffer. Returns the number of bytes read. ## write Write bytes from a buffer to a file descriptor. Returns the number of bytes written. **Terminal Control** ## ctermid Return the pathname of the controlling terminal. ## ttyname Return the name of the terminal device associated with a file descriptor. ## tcdrain / tcflow / tcflush / tcsendbreak / tcgetpgrp / tcsetpgrp Terminal I/O control functions for draining output, flow control, flushing, and process groups. **Locale** ## setlocale Set or query the program's locale. ```perl use POSIX 'setlocale'; setlocale(LC_ALL, "C"); ``` ## localeconv Return a hash reference of locale-specific numeric formatting conventions. **FP Comparison** ## isgreater / isgreaterequal / isless / islessequal / islessgreater / isunordered Floating-point comparison macros. Compare two NV values without raising FP exceptions on NaN. `isunordered` returns 1 if either argument is NaN. All return 1 (true) or 0 (false). ```perl use POSIX qw(isgreater isunordered NAN); isgreater(3.0, 2.0); # 1 isunordered(NAN, 1.0); # 1 ``` **Signal Handling** ## sigaction Install or query a signal handler for a given signal number. Stub implementation: returns 0 (success) without installing a C-level handler. For real signal handling, use Perl's `%SIG`. ```perl use POSIX qw(sigaction SIGINT); my $act = POSIX::SigAction->new('IGNORE'); sigaction(SIGINT, $act); ``` ## sigsuspend Temporarily replace the signal mask and suspend the process until a signal is delivered. Always returns -1 with errno EINTR. ```perl use POSIX qw(sigsuspend); my $set = POSIX::SigSet->new(); sigsuspend($set); ``` ## sigpending Store the set of currently pending signals into a SigSet object. Returns 0 on success, -1 on failure. ## sigprocmask Examine or change the process signal mask. `$how` is SIG_BLOCK, SIG_UNBLOCK, or SIG_SETMASK. Optionally stores the previous mask into `$oldsigset`. ```perl use POSIX qw(sigprocmask SIG_BLOCK SIGINT); my $new = POSIX::SigSet->new(SIGINT); my $old = POSIX::SigSet->new(); sigprocmask(SIG_BLOCK, $new, $old); ``` **POSIX::SigSet** ## SigSet::new Create a new signal set, optionally populated with the given signal numbers. Returns a blessed POSIX::SigSet object. ```perl use POSIX qw(SIGINT SIGTERM); my $set = POSIX::SigSet->new(SIGINT, SIGTERM); ``` ## SigSet::emptyset / SigSet::fillset Clear all signals from (or add all signals to) the set. Returns 0 on success. ## SigSet::addset / SigSet::delset Add or remove a single signal from the set. Returns 0 on success, -1 for out-of-range signal numbers. ## SigSet::ismember Test whether a signal is in the set. Returns 1 if present, 0 if absent. **POSIX::SigAction** ## SigAction::new Create a new signal action object with a handler, signal mask, flags, and optional safe flag. Returns a blessed POSIX::SigAction object. ```perl my $act = POSIX::SigAction->new(\&handler, $mask, SA_RESTART); ``` ## SigAction::handler / SigAction::mask / SigAction::flags / SigAction::safe Accessor/mutator methods for SigAction fields. Called with no argument to get the value, or with one argument to set it. **POSIX::Termios** ## Termios::new Create a new Termios object with all fields initialized to zero. Returns a blessed POSIX::Termios object. ```perl my $termios = POSIX::Termios->new(); ``` ## Termios::getattr Call `tcgetattr()` on the given file descriptor and store the result. Returns 0 on success, -1 on failure. ```perl $termios->getattr(fileno(STDIN)); ``` ## Termios::setattr Call `tcsetattr()` with the stored termios values and the given action (TCSANOW, TCSADRAIN, or TCSAFLUSH). ## Termios::getispeed / Termios::getospeed Return the stored input or output baud rate. ## Termios::setispeed / Termios::setospeed Set the input or output baud rate. ## Termios::getiflag / Termios::getoflag / Termios::getcflag / Termios::getlflag Return the stored input, output, control, or local mode flags. ## Termios::setiflag / Termios::setoflag / Termios::setcflag / Termios::setlflag Set the input, output, control, or local mode flags. ## Termios::getcc / Termios::setcc Get or set a control character by index (e.g., VEOF, VINTR). ```perl my $cc = $termios->getcc(VEOF); $termios->setcc(VEOF, 4); ``` **Math Builtins (re-exported)** ## pow / fabs / abs / sqrt / atan2 / cos / sin / exp / log Standard math functions re-exported through POSIX for compatibility. These delegate to the corresponding Perl builtins. **Process Identity** ## getpid / getppid Return the process ID or parent process ID. ## getuid / getgid / geteuid / getegid Return the real or effective user/group ID. ## getpgrp Return the process group ID of the calling process. ## isatty Test whether a file descriptor refers to a terminal. Returns 1 or 0. ```perl use POSIX 'isatty'; print "interactive\n" if isatty(0); ``` ## getlogin Return the login name associated with the current session, or undef. ## getenv Return the value of an environment variable, or undef if not set. **Character Classification** ## isalpha / isdigit / isalnum / isupper / islower / isspace / isprint / ispunct / iscntrl / isgraph / isxdigit Locale-aware character classification functions. Accept an integer (ordinal value of a character) and return 1 (true) or 0 (false). ```perl use POSIX qw(isdigit isalpha); isdigit(ord('5')); # 1 isalpha(ord('A')); # 1 ``` ## toupper / tolower Convert a character's ordinal value to upper or lower case according to the current locale. Returns the converted ordinal value. **User/Group Database** ## getpwnam / getpwuid Look up a password database entry by name or UID. Returns a 10-element list: (name, passwd, uid, gid, quota, comment, gecos, dir, shell, expire). Returns an empty list if not found. ```perl use POSIX 'getpwnam'; my @pw = getpwnam('root'); ``` ## getgrnam / getgrgid Look up a group database entry by name or GID. Returns a 4-element list: (name, passwd, gid, members). Returns an empty list if not found. **Additional File Operations** ## creat Create a new file or truncate an existing one. Equivalent to `open($path, O_WRONLY|O_CREAT|O_TRUNC, $mode)`. Returns a file descriptor or undef on failure. ## remove Remove a file or directory. Returns 1 on success, 0 on failure. ## rename Rename a file. Returns 1 on success, 0 on failure. ```perl use POSIX 'rename'; rename("old.txt", "new.txt"); ``` ## fcntl Perform a file control operation on a file descriptor. Returns the result value or undef on failure. ```perl use POSIX qw(fcntl F_GETFL); my $flags = fcntl($fd, F_GETFL, 0); ``` ## fileno Return the file descriptor number (pass-through). ## errno Return the current value of the C errno variable. ```perl use POSIX 'errno'; my $err = errno(); ``` **Perl Builtin Re-exports** ## sprintf / printf Format strings using Perl's sprintf/printf. Re-exported through POSIX for compatibility with code that imports them from POSIX. ## alarm Schedule a SIGALRM signal after the specified number of seconds. Returns the number of seconds remaining from a previous alarm. ## exit Terminate the process with the given exit code. ## chdir Change the current working directory. Returns 1 on success, 0 on failure. ## kill Send a signal to a process. Returns the result of the underlying kill(2) call. ## fork Create a child process. Returns the child PID to the parent, 0 to the child, or undef on failure. ## wait / waitpid Wait for a child process to change state. `wait` waits for any child; `waitpid` waits for a specific PID with the given flags (e.g., WNOHANG). ## time Return the current epoch time in seconds. ## umask Set the file creation mask. Returns the previous mask value. ## link / unlink Create or remove a hard link. Returns 1 on success, 0 on failure. ## mkdir / rmdir Create or remove a directory. Returns 1 on success, 0 on failure. ## chmod Change file permissions. Returns 1 on success, 0 on failure. ## system Execute a shell command. Returns the exit status of the command. ## srand Seed the C library random number generator. Perl equivalent: POSIX