### Example Usage of msgctl, msgget, and msgctl with IPC_STAT and IPC_RMID
Source: https://luaposix.github.io/luaposix/modules/posix.sys.msg.html
Demonstrates how to get a message queue identifier, check its status using IPC_STAT, and then remove it using IPC_RMID. Ensure the module and necessary constants are required.
```lua
local sysvmsg = require 'posix.sys.msg'
local msq = sysvmsg.msgget(sysvmsg.IPC_PRIVATE)
local msqid, errmsg = sysvmsg.msgctl(msq, sysvmsg.IPC_STAT)
assert(msqid, errmsg)
assert(sysvmsg.msgctl(msq, sysvmsg.IPC_RMID))
```
--------------------------------
### Get system configuration values
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Retrieves system configuration information at runtime using predefined keys. Useful for querying system limits and parameters.
```lua
-- Example usage for sysconf()
-- local pagesize = unistd.sysconf('_SC_PAGESIZE')
-- if pagesize then
-- print("System page size:", pagesize)
-- else
-- print("Error retrieving system configuration")
-- end
```
--------------------------------
### Create Socket Example
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Shows how to create a socket endpoint for communication using the socket function. Requires specifying the domain (e.g., AF_INET), type (e.g., SOCK_STREAM), and options.
```lua
local sys_sock = require "posix.sys.socket"
sockd = sys_sock.socket (sys_sock.AF_INET, sys_sock.SOCK_STREAM, 0)
```
--------------------------------
### Signal Handling Example
Source: https://luaposix.github.io/luaposix/examples/signal.lua.html
Demonstrates setting up signal handlers for SIGCHLD, SIGUSR1, SIGUSR2, and a custom signal (60). It forks child processes that send signals back to the parent, and the parent process collects and asserts the signal counts.
```lua
#! /usr/bin/env lua
local M = require 'posix.signal'
local unistd = require 'posix.unistd'
local syswait = require 'posix.sys.wait'
local function go(fn, ...)
local childpid = unistd.fork()
if childpid == 0 then -- run function as child
unistd._exit(fn(...) or 0)
else
return childpid
end
end
local verbose = #arg > 0
local function sleepx(secs)
while true do
secs = unistd.sleep(secs)
if verbose then
print('sleep', secs)
end
if secs == 0 then
return
end
end
end
local nchild, nsig = 0, 0
M.signal(M.SIGCHLD, function()
local pid, status, code = syswait.wait(-1, syswait.WNOHANG)
while pid do
if pid ~= 0 then
if verbose then
print('wait', pid, status, code)
end
nchild = nchild + 1
end
pid, status, code = syswait.wait(-1, syswait.WNOHANG)
end
end)
local function handler(signo)
if verbose then
print('handled', signo)
end
nsig = nsig + 1
end
M.signal(M.SIGUSR1, handler)
M.signal(M.SIGUSR2, handler)
M.signal(60, handler)
local function killp(nsig)
return M.kill(unistd.getppid(), nsig)
end
c1 = go(function() unistd.sleep(1); killp(M.SIGUSR1); killp(M.SIGUSR2) end)
c2 = go(function() unistd.sleep(2); killp(M.SIGUSR2); end)
c3 = go(function() unistd.sleep(2); killp(M.SIGUSR1) end)
sleepx(3)
if verbose then
print('children', nchild, 'signals', nsig)
else
assert(nchild == 3)
assert(nsig == 4)
print '+++ tests OK +++'
end
```
--------------------------------
### Create Socket Pair Example
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Demonstrates creating a pair of connected sockets using the socketpair function. This is useful for inter-process communication. Specify the domain, socket type, and options.
```lua
local sys_sock = require "posix.sys.socket"
sockr, sockw = sys_sock.socketpair (sys_sock.AF_INET, sys_sock.SOCK_STREAM, 0)
```
--------------------------------
### Set Socket Option Example
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Demonstrates how to set a socket option, specifically the send timeout, using the setsockopt function. Requires the socket descriptor, level, name, and value(s) as arguments.
```lua
local sys_sock = require "posix.sys.socket"
ok, errmsg = sys_sock.setsockopt (
sock, sys_sock.SOL_SOCKET, sys_sock.SO_SNDTIMEO, 1, 0
)
```
--------------------------------
### Get File System Statistics
Source: https://luaposix.github.io/luaposix/modules/posix.sys.statvfs.html
Demonstrates how to retrieve and iterate over file system statistics for the root directory using the statvfs function. Requires the posix.sys.statvfs module to be loaded.
```lua
local statvfs = require "posix.sys.statvfs".statvfs
for a, b in pairs (statvfs "/") do print (a, b) end
```
--------------------------------
### umask
Source: https://luaposix.github.io/luaposix/modules/posix.html
Sets or gets the file mode creation mask.
```APIDOC
## umask ([mode])
### Description
Set file mode creation mask.
### Parameters
* mode (string) - file creation mask string (optional)
### Returns
* (string) - previous umask
```
--------------------------------
### pathconf
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Get a value for a configuration option for a filename. It takes a path and a key representing the configuration option.
```APIDOC
## pathconf (path, key)
### Description
Get a value for a configuration option for a filename.
### Parameters:
* path (string) - optional
* key (int) - one of `_PC_LINK_MAX`, `_PC_MAX_CANON`, `_PC_NAME_MAX`, `_PC_PIPE_BUF`, `_PC_CHOWN_RESTRICTED`, `_PC_NO_TRUNC` or `_PC_VDISABLE`
### Returns:
int associated path configuration value
```
--------------------------------
### posix.unistd Functions
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
This section details the functions available in the posix.unistd module, covering process termination, file permissions, alarms, directory changes, file ownership, file descriptor operations, password encryption, command execution, file synchronization, forking, file truncation, getting current working directory, user and group IDs, host ID, command-line option parsing, process group and ID, terminal checks, symbolic link handling, directory removal, process ID and group setting, sleeping, buffer cache synchronization, system configuration, terminal foreground process group, and file unlinking and writing.
```APIDOC
## Module `posix.unistd`
Unix Standard APIs.
Where the underlying system does not support one of these functions, it will have a `nil` value in the module table.
### Functions
- **_exit (status)**: Terminate the calling process.
- **access (path[, mode="f"])**: Check real user's permissions for a file.
- **alarm (seconds)**: Schedule an alarm signal.
- **chdir (path)**: Set the working directory.
- **chown (path, uid, gid)**: Change ownership of a file.
- **close (fd)**: Close an open file descriptor.
- **crypt (trypass, salt)**: Encrypt a password.
- **dup (fd)**: Duplicate an open file descriptor.
- **dup2 (fd, newfd)**: Duplicate one open file descriptor to another.
- **exec (path, argt)**: Execute a program at exactly _path_.
- **execp (path, argt)**: Execute a program found using command PATH search, like the shell.
- **fdatasync (fd)**: Synchronize a file's in-core state with storage device without metadata.
- **fork ()**: Fork this program.
- **fsync (fd)**: Synchronize a file's in-core state with storage device.
- **ftruncate (fd, length)**: Truncate a file to a specified length.
- **getcwd ()**: Current working directory for this process.
- **getegid ()**: Return effective group id of calling process.
- **geteuid ()**: Return effective user id of calling process.
- **getgid ()**: Return group id of calling process.
- **getgroups ()**: Get list of supplementary group ids.
- **gethostid ()**: Get host id.
- **getopt (arg, opts[, opterr=0[, optind=1]])**: Parse command-line options.
- **getpgrp ()**: Return process group id of calling process.
- **getpid ()**: Return process id of calling process.
- **getppid ()**: Return parent process id of calling process.
- **getuid ()**: Return user id of calling process.
- **isatty (fd)**: Test whether a file descriptor refers to a terminal.
- **lchown (path, uid, gid)**: This is like `chown`, but does not dereference symbolic links.
- **link (target, link[, soft=false])**: Create a link.
- **linkat (targetdir, target, linkdir, link, flags)**: Create a link at specified directory.
- **lseek (fd, offset, whence)**: reposition read/write file offset
- **nice (inc)**: change process priority
- **pathconf (path, key)**: Get a value for a configuration option for a filename.
- **pipe ()**: Creates a pipe.
- **read (fd, count)**: Read bytes from a file.
- **readlink (path)**: Read value of a symbolic link.
- **rmdir (path)**: Remove a directory.
- **setpid (what, id[, gid])**: Set the uid, euid, gid, egid, sid or pid & gid.
- **sleep (seconds)**: Sleep for a number of seconds.
- **sync ()**: Commit buffer cache to disk.
- **sysconf (key)**: Get configuration information at runtime.
- **tcgetpgrp (fd)**: Get id of foreground process group of terminal _fd_.
- **tcsetpgrp (fd, pgid)**: Make process group _pgid_ the foreground process group of terminal _fd_.
- **truncate (path, length)**: Truncate a file to a specified length.
- **ttyname ([fd=0])**: Name of a terminal device.
- **unlink (path)**: Unlink a file.
- **write (fd, buf[, nbytes=#buf[, offset=0]])**: Write bytes to a file.
```
--------------------------------
### setsockopt
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Gets and sets options on sockets. It allows configuration of various socket parameters like timeouts.
```APIDOC
## setsockopt (fd, level, name, value1[, value2])
### Description
Get and set options on sockets.
### Parameters
* **fd** (int) - socket descriptor
* **level** (int) - one of `SOL_SOCKET`, `IPPROTO_IPV6`, `IPPROTO_TCP`
* **name** (int) - option name, varies according to `level` value
* **value1** (any) - option value to set
* **value2** (any) - some option _name_ s need an additional value (_optional_)
### Returns
* **int** `0`, if successful
* **nil**, **string** error message, **int** errnum on failure
### Usage:
```lua
local sys_sock = require "posix.sys.socket"
ok, errmsg = sys_sock.setsockopt (
sock, sys_sock.SOL_SOCKET, sys_sock.SO_SNDTIMEO, 1, 0
)
```
```
--------------------------------
### Shutdown Socket Connection Example
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Illustrates how to shut down a part of a full-duplex connection using the shutdown function. Specify the socket descriptor and the how parameter (SHUT_RD, SHUT_WR, or SHUT_RDWR).
```lua
local sys_sock = require "posix.sys.socket"
ok, errmsg = sys_sock.shutdown (sock, sys_sock.SHUT_RDWR)
```
--------------------------------
### TCP Client for Fetching Website Title
Source: https://luaposix.github.io/luaposix/examples/socket.lua.html
This snippet demonstrates how to create a TCP client socket, connect to a web server, send an HTTP GET request, and receive the response to extract the website title. It uses getaddrinfo for address resolution and handles SIGPIPE signals.
```lua
#! /usr/bin/env lua
local M = require 'posix.sys.socket'
local sig = require 'posix.signal'
sig.signal(sig.SIGPIPE, function() print 'pipe' end)
-- Get Lua web site title
local r, err = M.getaddrinfo('www.lua.org', 'http', {family=M.AF_INET, socktype=M.SOCK_STREAM})
if not r then
error(err)
end
local fd = M.socket(M.AF_INET, M.SOCK_STREAM, 0)
local ok, err, e = M.connect(fd, r[1])
local sa = M.getsockname(fd)
print('Local socket bound to ' .. sa.addr .. ':' .. tostring(sa.port))
if err then
error(err)
end
M.send(fd, 'GET / HTTP/1.0\r\nHost: www.lua.org\r\n\r\n')
local data = {}
while true do
local b = M.recv(fd, 1024)
if not b or #b == 0 then
break
end
table.insert(data, b)
end
require 'posix.unistd'.close(fd)
data = table.concat(data)
print(string.match(data, '
(.+)'))
```
--------------------------------
### Get File Information with stat
Source: https://luaposix.github.io/luaposix/modules/posix.sys.stat.html
Retrieve file status information using `stat`, which returns information about the file a symbolic link points to. Iterates through the returned `PosixStat` table.
```lua
local sys_stat = require "posix.sys.stat"
for a, b in pairs (sys_stat.stat "/etc/") do print (a, b) end
```
--------------------------------
### Get File Status Flags with fcntl
Source: https://luaposix.github.io/luaposix/modules/posix.fcntl.html
Demonstrates how to retrieve the current file status flags for a given file descriptor using the `fcntl` function with the `F_GETFL` command.
```lua
local flag = posix.fcntl (fd, posix.F_GETFL)
```
--------------------------------
### Get File Information with fstat
Source: https://luaposix.github.io/luaposix/modules/posix.sys.stat.html
Retrieve detailed file status information using `fstat` with an open file descriptor. The returned `PosixStat` table contains various file attributes. Requires `posix.fcntl` for opening files.
```lua
local fcntl = require "posix.fcntl"
local sys_stat = require "posix.sys.stat"
local fd = assert(fcntl.open("/etc/hostname", fcntl.O_RDONLY))
for a, b in pairs (sys_stat.fstat(fd)) do print (a, b) end
```
--------------------------------
### Redirecting stdout and stderr with dup2
Source: https://luaposix.github.io/luaposix/examples/dup2.lua.html
This example uses fork to create a child process. In the child, dup2 is used to redirect stdout and stderr to separate pipes. The parent process then reads from these pipes to capture the output of the child. Ensure the 'posix.unistd' module is required.
```lua
#! /usr/bin/env lua
local M = require 'posix.unistd'
local function pipe()
local r, w = M.pipe()
assert(r ~= nil, w)
return r, w
end
local stdout_r, stdout_w = pipe()
local stderr_r, stderr_w = pipe()
local pid, errmsg = M.fork()
assert(pid ~= nil, errmsg)
if pid == 0 then
-- Child Process:
M.close(stdout_r)
M.close(stderr_r)
M.dup2(stdout_w, M.STDOUT_FILENO)
M.dup2(stderr_w, M.STDERR_FILENO)
-- Exec() a subprocess here instead if you like --
io.stdout:write 'output string'
io.stderr:write 'oh noes!'
os.exit(42)
else
-- Parent Process:
M.close(stdout_w)
M.close(stderr_w)
local function read(msg, fd)
local outs, errmsg = M.read(fd, 1024)
assert(outs ~= nil, errmsg)
print(msg, outs)
end
read('STDOUT:', stdout_r)
read('STDERR:', stderr_r)
local childpid, reason, status = require 'posix.sys.wait'.wait(pid)
assert(childpid ~= nil, reason)
print('child ' .. reason, status)
end
```
--------------------------------
### signal
Source: https://luaposix.github.io/luaposix/modules/posix.signal.html
Installs a signal handler for a given signal number. This function uses sigaction for consistent semantics across platforms. It accepts the signal number, a handler function (or SIG_IGN/SIG_DFL), and optional flags.
```APIDOC
## signal
### Description
Install a signal handler for this signal number. Although this is the same API as signal(2), it uses sigaction for guaranteed semantics.
### Parameters:
* signum (int) - The signal number.
* handler (function | constant) - The handler function, or `SIG_IGN` or `SIG_DFL` constants. Defaults to `SIG_DFL`.
* flags (int) - Optional flags for `struct sigaction`.
### Returns:
* function - The previous handler function.
```
--------------------------------
### Test sched_setscheduler and sched_getscheduler on current process
Source: https://luaposix.github.io/luaposix/examples/rt_sched.lua.html
This snippet tests setting and getting scheduling policies and priorities for the current process. It verifies SCHED_OTHER, SCHED_FIFO, and SCHED_RR policies using ps command for verification. The script must be run as a privileged process.
```lua
#! /usr/bin/env lua
--[[
This example tests sched_setscheduler() / sched_getscheduler()
The script must be run as privileged process (CAP_SYS_NICE)
]]
local M = require 'posix.sched'
local mypid = require 'posix.unistd'.getpid()
-- get sched params from ps(1)
local function get_ps_sched(pid)
local fp = io.popen(string.format('ps --no-headers -o "policy,rtprio" %s', pid))
local res, err = fp:read'*a'
assert(res, err)
fp:close()
local policy, rtprio = string.match(res, '([^%s]+)%s+([^%s]+)')
assert(policy)
assert(rtprio)
return policy, rtprio
end
do -- Tests on own process
-- get scheduler policy for own process
local res, err = M.sched_getscheduler(0) -- 0 pid: own process
assert(res == M.SCHED_OTHER)
local res, err = M.sched_getscheduler() -- default pid: own process
assert(res == M.SCHED_OTHER)
local policy, rtprio = get_ps_sched(mypid)
assert(policy== 'TS')
assert(rtprio== '-')
-- set realtime priority on own process : SCHED_FIFO
local res, err = M.sched_setscheduler(0, p.SCHED_FIFO, 10 )
assert(res, err)
local policy, rtprio = get_ps_sched(mypid)
assert(policy == 'FF')
assert(rtprio == '10')
local res, err = M.sched_getscheduler(0)
assert(res == M.SCHED_FIFO)
-- set realtime priority on own process SCHED_RR
local res, err = M.sched_setscheduler(0, M.SCHED_RR, 11 )
assert(res, err)
local policy, rtprio = get_ps_sched(mypid)
assert(policy == 'RR')
assert(rtprio == '11')
local res, err = M.sched_getscheduler(0)
assert(res == M.SCHED_RR)
-- no parameters: reset own process to normal priority :
local res, err = M.sched_setscheduler()
assert(res, err)
local policy, rtprio = get_ps_sched(mypid)
assert(policy == 'TS')
assert(rtprio == '-')
local res, err = M.sched_getscheduler(0)
assert(res == M.SCHED_OTHER)
end
```
--------------------------------
### Get Socket Option (Send Timeout)
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Retrieves the value of a specific socket option. This example shows how to get the send timeout value for a socket.
```lua
local sys_sock = require "posix.sys.socket"
val, errmsg, errnum = sys_sock.getsockopt(
sock, sys_sock.SOL_SOCKET, sys_sock.SO_SNDTIMEO
)
print('Send timeout ', val.tv_sec + val.tv_usec / 1000000)
```
--------------------------------
### Make Directory
Source: https://luaposix.github.io/luaposix/modules/posix.html
Creates a new directory at the specified path.
```lua
mkdir('new_directory')
```
--------------------------------
### tcgetpgrp
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Gets the foreground process group ID of a terminal.
```APIDOC
## tcgetpgrp (fd)
### Description
Get id of foreground process group of terminal _fd_.
### Parameters:
* fd (int) - the file descriptor of the controlling terminal of the current process
### Returns:
int id of foreground process group, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
tcgetpgrp(2)
```
--------------------------------
### creat (path, mode)
Source: https://luaposix.github.io/luaposix/modules/posix.html
Creates a new file with the specified path and permissions. This function is considered obsolete and `posix.fcntl.open` with `posix.O_CREAT` is recommended instead.
```APIDOC
## creat (path, mode)
### Description
Creates a new file with the specified path and permissions. This function is considered obsolete and `posix.fcntl.open` with `posix.O_CREAT` is recommended instead.
### Parameters:
* `path` (string) - The name of the file to create.
* `mode` (string) - The permissions with which to create the file.
### Returns:
* `int` - Returns the file descriptor of the created file if successful.
* `nil`, `string`, `int` - Returns `nil`, an error message string, and an error number if the operation fails.
### See also:
* creat(2)
* posix.chmod
### Usage:
```lua
fd = creat('data', 'rw-r-----')
```
```
--------------------------------
### Open a File with Specific Flags and Permissions
Source: https://luaposix.github.io/luaposix/modules/posix.fcntl.html
Shows how to open a file named 'data' with read/write permissions and create it if it doesn't exist, also setting specific user permissions.
```lua
local P = require "posix.fcntl"
fd = P.open ("data", bit.bor (P.O_CREAT, P.O_RDWR), bit.bor (P.S_IRWXU, P.S_IRGRP))
```
--------------------------------
### gethostid
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Get the host ID. Returns the host ID as an integer on success.
```APIDOC
## gethostid ()
### Description
Get host id.
### Returns:
int host id, if successful
### Or
1. nil
2. string error message
### See also:
gethostid(3)
```
--------------------------------
### setpwent
Source: https://luaposix.github.io/luaposix/modules/posix.pwd.html
Resets the password database iterator to the beginning. This allows getpwent to be called again from the start of the database.
```APIDOC
## setpwent
### Description
Rewinds the getpwent iterator back to the start of the database.
### See also:
* setpwent(3)
* getpwent
```
--------------------------------
### Create File
Source: https://luaposix.github.io/luaposix/modules/posix.html
Creates a new file with specified permissions. This function is considered obsolete and posix.fcntl.open with O_CREAT is recommended.
```lua
fd = creat('data', 'rw-r-----')
```
--------------------------------
### getcwd
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Get the current working directory for the process. It returns the path of the current working directory as a string.
```APIDOC
## getcwd ()
### Description
Current working directory for this process.
### Returns:
string path of current working directory, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
getcwd(3)
```
--------------------------------
### listen (fd, backlog)
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Enables a socket to accept incoming connections.
```APIDOC
## listen (fd, backlog)
### Description
Listen for connections on a socket.
### Parameters:
* fd int socket descriptor to act on
* backlog int maximum length for queue of pending connections
### Returns:
int `0`, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
listen(2)
```
--------------------------------
### time
Source: https://luaposix.github.io/luaposix/modules/posix.time.html
Gets the current system time as seconds since the epoch. It returns an integer representing the time.
```APIDOC
## time ()
### Description
Get current time.
### Returns:
* **int** - Time in seconds since epoch, if successful
* **nil**
* **string** - Error message
* **int** - Error number
### See also:
time(2)
```
--------------------------------
### getgroups
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Get the list of supplementary group IDs for the calling process. Returns a table of group IDs on success.
```APIDOC
## getgroups ()
### Description
Get list of supplementary group ids.
### Returns:
table group id, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
getgroups(2)
```
--------------------------------
### Get Terminal Attributes
Source: https://luaposix.github.io/luaposix/modules/posix.termio.html
Retrieves the current termios state for a given file descriptor. Use this to inspect terminal settings.
```lua
local termios, errmsg = tcgetattr (fd)
```
--------------------------------
### mkdir
Source: https://luaposix.github.io/luaposix/modules/posix.sys.stat.html
Creates a new directory at the specified path with optional mode.
```APIDOC
## mkdir (path[, mode=511])
### Description
Make a directory.
### Parameters:
* path (string) - location in file system to create directory
* mode (int) - access modes to set for _path_ (_default_ 511)
### Returns:
* int - `0`, if successful
* nil, string error message, int errnum - if an error occurs
### See also:
mkdir(2)
```
--------------------------------
### sysconf
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Retrieves system configuration values at runtime.
```APIDOC
## sysconf (key)
### Description
Get configuration information at runtime.
### Parameters:
* key (int) - one of `_SC_ARG_MAX`, `_SC_CHILD_MAX`, `_SC_CLK_TCK`, `_SC_JOB_CONTROL`, `_SC_OPEN_MAX`, `_SC_NGROUPS_MAX`, `_SC_SAVED_IDS`, `_SC_STREAM_MAX`, `_SC_PAGESIZE`, `_SC_TZNAME_MAX` or `_SC_VERSION`
### Returns:
int associated system configuration value
### See also:
sysconf(3)
```
--------------------------------
### Get Socket Name
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Retrieves the local address to which a socket is bound. Use this to determine the address and port the socket is listening on or connected to.
```lua
sa, err = posix.getsockname (sockfd)
```
--------------------------------
### mkstemp
Source: https://luaposix.github.io/luaposix/modules/posix.stdlib.html
Creates a unique temporary file based on a provided template string and returns an open file descriptor.
```APIDOC
## mkstemp
### Description
Create a unique temporary file.
### Parameters:
* `templ` (string) - Template pattern that must end in six 'X' characters.
### Returns:
* `fd` (int) - An open file descriptor for the temporary file, if successful.
* `path` (string) - The path to the temporary file, if successful.
* `nil`, `error message` (string), `errnum` (int) - If an error occurs.
### See also:
mkstemp(3)
### Usage:
```lua
local stdlib = require "posix.stdlib"
stdlib.mkstemp 'wooXXXXXX'
```
```
--------------------------------
### Get Peer Name
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Retrieves the address of the connected peer for a given socket descriptor. This is useful for identifying the remote end of a connection.
```lua
sa, err = posix.getpeername (sockfd)
```
--------------------------------
### Get the name of a terminal device
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Returns the name of the terminal device associated with a given file descriptor. Defaults to file descriptor 0 if not specified.
```lua
-- Example usage for ttyname()
-- local tty_name = unistd.ttyname(fd)
-- if tty_name then
-- print("Terminal device name:", tty_name)
-- else
-- print("Error getting terminal device name")
-- end
```
--------------------------------
### open
Source: https://luaposix.github.io/luaposix/modules/posix.fcntl.html
Open a file. This function opens a specified file with given flags and an optional mode, returning a file descriptor.
```APIDOC
## open (path, oflags[, mode=511])
### Description
Open a file. Opens a specified file with given flags and an optional mode, returning a file descriptor.
### Parameters
* **path** (string) - The path to the file.
* **oflags** (int) - Bitwise OR of zero or more of `O_RDONLY`, `O_WRONLY`, `O_RDWR`, `O_APPEND`, `O_CREAT`, `O_DSYNC`, `O_EXCL`, `O_NOCTTY`, `O_NONBLOCK`, `O_RSYNC`, `O_SYNC`, and `O_TRUNC` (and `O_CLOEXEC`, where supported).
* **mode** (int) - Access modes used by `O_CREAT`. Defaults to 511.
### Returns
* int - File descriptor for the path, if successful.
* nil, string, int - On failure, returns nil, an error message, and an error number.
### See also
open(2)
### Usage
```lua
local P = require "posix.fcntl"
fd = P.open ("data", bit.bor (P.O_CREAT, P.O_RDWR), bit.bor (P.S_IRWXU, P.S_IRGRP))
```
```
--------------------------------
### nice
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Change the process priority by adjusting its nice value. It takes an integer increment as input.
```APIDOC
## nice (inc)
### Description
change process priority
### Parameters:
* inc (int) - adds inc to the nice value for the calling process
### Returns:
int new nice value, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
nice(2)
```
--------------------------------
### Get Message Queue Identifier
Source: https://luaposix.github.io/luaposix/modules/posix.html
Retrieves an identifier for a message queue. Can create a new queue if IPC_CREAT flag is used. Default mode is 'rw-rw-rw-'.
```lua
msgget(key, flags, mode)
```
--------------------------------
### Get NoFile Resource Limit
Source: https://luaposix.github.io/luaposix/modules/posix.sys.resource.html
Retrieves the current soft limit for the maximum number of open files for the process. Requires importing the posix.sys.resource module.
```lua
local sysres = require "posix.sys.resource"
sysres.getrlimit(sysres.RLIMIT_NOFILE)
```
--------------------------------
### Open File with Flags and Mode
Source: https://luaposix.github.io/luaposix/modules/posix.html
Opens a file with specified access flags and creation mode. Combines standard POSIX open flags using bitwise OR.
```lua
fd = posix.open('data', bit.bor(posix.O_CREAT, posix.O_RDWR), 'rw-r-----')
```
--------------------------------
### Get Address Info
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Translates network host and service names into socket address structures. Use this to resolve hostnames and service names for socket operations.
```lua
local sys_sock = require "posix.sys.socket"
local res, errmsg, errcode = sys_sock.getaddrinfo ("www.lua.org", "http",
{ family = sys_sock.IF_INET, socktype = sys_sock.SOCK_STREAM }
)
```
--------------------------------
### statvfs
Source: https://luaposix.github.io/luaposix/modules/posix.sys.statvfs.html
Gets file system statistics for a given path. It returns a table containing detailed information about the file system or an error message and code if it fails.
```APIDOC
## statvfs
### Description
Get file system statistics.
### Method
`statvfs(path)`
### Parameters
#### Path Parameters
- **path** (string) - Required - Any path within the mounted file system.
### Returns
- **PosixStatvfs** (table) - Information about the file system containing `path`, if successful.
- **nil**, **string**, **int** - If an error occurs, returns nil, an error message, and an error number.
### See also:
statvfs(3)
### Usage:
```lua
local statvfs = require "posix.sys.statvfs".statvfs
for a, b in pairs (statvfs "/") do print (a, b) end
```
```
--------------------------------
### connect (fd, addr)
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Initiates a connection from a socket descriptor to a specified address.
```APIDOC
## connect (fd, addr)
### Description
Initiate a connection on a socket.
### Parameters:
* fd int socket descriptor to act on
* addr sockaddr socket address
### Returns:
int `0`, if successful
### Or
1. nil
2. string error message
3. int errnum
### See also:
connect(2)
```
--------------------------------
### Describe current errno
Source: https://luaposix.github.io/luaposix/modules/posix.errno.html
Call `posix.errno()` without arguments to get the description and code of the current system error. This is useful for debugging failed system calls.
```lua
local strerr, nerr = posix.errno ()
```
--------------------------------
### spawn
Source: https://luaposix.github.io/luaposix/modules/posix.html
Runs a command or function in a sub-process using posix.execx.
```APIDOC
## spawn (task, ...)
### Description
Run a command or function in a sub-process using posix.execx.
### Parameters
* task (table or function) - argument list for posix.unistd.execp or a Lua function, which should read from standard input, write to standard output, and return an exit code
* ... - as for posix.execx
### Returns
* (int, string) - exit status, or signal number responsible for "killed" or "stopped"
* (int, string) - errnum, error message
```
--------------------------------
### Get Terminal Window Size
Source: https://luaposix.github.io/luaposix/modules/posix.termio.html
Fetches the current terminal window size (rows, columns, pixel dimensions) for a file descriptor. Requires importing the posix.termio module.
```lua
local termio = require "posix.termio"
local ws, errmsg, errnum = termio.tcgetwinsize(fd)
if ws then
print("rows=", ws.row, "cols=", ws.col, "xpixel=", ws.xpixel, "ypixel=", ws.ypixel)
else
print("Error: ", errmsg, errnum)
end
```
--------------------------------
### List Directory Contents with posix.dirent
Source: https://luaposix.github.io/luaposix/examples/dir.lua.html
This snippet demonstrates how to list the contents of the '/var/log' directory using the `posix.dirent.dir` function. It includes error handling for cases where the directory might not be accessible.
```lua
#! /usr/bin/env lua
local M = require 'posix.dirent'
local ok, files = pcall(M.dir, '/var/log')
if not ok then
print('/var/log: ' .. files)
end
for _, f in ipairs(files) do
print(f)
end
```
--------------------------------
### open (path, oflags, modestr)
Source: https://luaposix.github.io/luaposix/modules/posix.html
Opens a file specified by `path` with given `oflags` and `modestr`. `oflags` is a bitwise OR of constants like `O_RDONLY`, `O_CREAT`, etc. `modestr` is used when creating files.
```APIDOC
## open (path, oflags, modestr)
### Description
Opens a file specified by `path` with given `oflags` and `modestr`. `oflags` is a bitwise OR of constants like `O_RDONLY`, `O_CREAT`, etc. `modestr` is used when creating files.
### Parameters:
* `path` (string) - The file to act on.
* `oflags` (int) - Bitwise OR of zero or more of the following flags: `O_RDONLY`, `O_WRONLY`, `O_RDWR`, `O_APPEND`, `O_CREAT`, `O_DSYNC`, `O_EXCL`, `O_NOCTTY`, `O_NONBLOCK`, `O_RSYNC`, `O_SYNC`, `O_TRUNC`.
* `modestr` (string) - The permission mode string, used with `O_CREAT`. See `chmod` for format.
### Returns:
* `int` - The file descriptor for the opened `path` if successful.
* `nil`, `string`, `int` - Returns `nil`, an error message string, and an error number if the operation fails.
### See also:
open(2)
### Usage:
```lua
fd = posix.open('data', bit.bor(posix.O_CREAT, posix.O_RDWR), 'rw-r-----')
```
```
--------------------------------
### mkdir (path)
Source: https://luaposix.github.io/luaposix/modules/posix.html
Creates a new directory at the specified path in the file system.
```APIDOC
## mkdir (path)
### Description
Creates a new directory at the specified path in the file system.
### Parameters:
* `path` (string) - The location in the file system where the directory should be created.
### Returns:
* `int` - Returns `0` if the directory was created successfully.
* `nil`, `string`, `int` - Returns `nil`, an error message string, and an error number if the operation fails.
```
--------------------------------
### Parse Command-Line Options with getopt
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Iterates through command-line arguments to parse options using the getopt function. Requires the 'posix.getopt' module.
```lua
local getopt = require "posix.getopt".getopt
for opt, opterr, i in getopt (arg, "ho:v", opterr, i) do
process (arg, opterr, i)
end
```
--------------------------------
### times
Source: https://luaposix.github.io/luaposix/modules/posix.sys.times.html
Get the current process times. Returns a PosixTms table with time accounting information for the current process, or an error message and error number if the call fails.
```APIDOC
## times ()
### Description
Get the current process times. This function returns a table containing time accounting information for the current process.
### Returns:
- PosixTms: A table containing time accounting information for the process if successful.
- nil, string, int: If an error occurs, returns nil, an error message string, and an error number.
### See also:
- times(2)
```
--------------------------------
### execp
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Execute a program found by searching the system's PATH environment variable, similar to how the shell executes commands.
```APIDOC
## execp
### Description
Execute a program found using command PATH search, like the shell.
### Parameters
* **path** (string)
* **argt** (table) - arguments (table can include index 0)
### Returns
* **nil**
* **error message** (string)
* **error number** (int)
```
--------------------------------
### Parsing Command-Line Arguments with getopt
Source: https://luaposix.github.io/luaposix/examples/getopt.lua.html
This snippet shows how to use `posix.unistd.getopt` to parse command-line arguments. It handles options like '-h', '-a', and '-s', including options with required arguments. The loop iterates through the arguments, processing recognized options and storing the index of the first non-option argument.
```lua
#! /usr/bin/env lua
local getopt = require 'posix.unistd'.getopt
local last_index = 1
for r, optarg, optind in getopt(arg, 'ha:s:') do
if r == '?' then
return print('unrecognized option', arg[optind -1])
end
last_index = optind
if r == 'h' then
print '-h print this help text'
print '-a ARG a flag with required argument'
print '-s ARG a different flag with a required argument'
elseif r == 'a' or r == 's' then
print('we were passed', r, optarg)
end
end
for i = last_index, #arg do
print(i, arg[i])
end
```
--------------------------------
### uname
Source: https://luaposix.github.io/luaposix/modules/posix.sys.utsname.html
Returns information about the current machine, including hardware platform, network node name, operating system release and version, and operating system name.
```APIDOC
## uname
### Description
Returns information about the current machine.
### Method
N/A (Lua function)
### Parameters
None
### Returns
- **utsname** (table) - System identification information if successful.
- **machine** (string) - Hardware platform name.
- **nodename** (string) - Network node name.
- **release** (string) - Operating system release level.
- **sysname** (string) - Operating system name.
- **version** (string) - Operating system version.
- **nil**
- **error message** (string)
- **errnum** (int)
```
--------------------------------
### Parse Date String with strptime
Source: https://luaposix.github.io/luaposix/modules/posix.time.html
Parses a date string using a specified format and returns a broken-down local time. The example demonstrates checking the parsed month day.
```lua
posix.strptime('20','%d').monthday == 20
```
--------------------------------
### exec
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Execute a program at a specified absolute path. The current process image is replaced.
```APIDOC
## exec
### Description
Execute a program at exactly _path_.
### Parameters
* **path** (string)
* **argt** (table) - arguments (table can include index 0)
### Returns
* **nil**
* **error message** (string)
* **error number** (int)
### Usage
```lua
exec ("/bin/bash", {[0] = "-sh", "--norc"})
```
```
--------------------------------
### Create a pipe
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Creates a pipe for inter-process communication. Returns the read and write file descriptors.
```lua
-- Example usage for pipe()
-- local read_fd, write_fd = unistd.pipe()
-- if read_fd then
-- print("Pipe created: read_fd=", read_fd, "write_fd=", write_fd)
-- else
-- print("Error creating pipe")
-- end
```
--------------------------------
### Get foreground process group ID of a terminal
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Retrieves the process group ID of the foreground process associated with a given terminal file descriptor. Returns an error if the operation fails.
```lua
-- Example usage for tcgetpgrp()
-- local pgid = unistd.tcgetpgrp(fd)
-- if pgid then
-- print("Foreground process group ID:", pgid)
-- else
-- print("Error getting foreground process group ID")
-- end
```
--------------------------------
### mkdtemp
Source: https://luaposix.github.io/luaposix/modules/posix.stdlib.html
Creates a unique temporary directory based on a provided template string.
```APIDOC
## mkdtemp
### Description
Create a unique temporary directory.
### Parameters:
* `templ` (string) - Template pattern that must end in six 'X' characters.
### Returns:
* `path` (string) - The path to the created directory, if successful.
* `nil`, `error message` (string), `errnum` (int) - If an error occurs.
### See also:
mkdtemp(3)
```
--------------------------------
### Get Network Interface Index
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Converts a network interface name to its corresponding index. This is necessary for certain socket operations like binding to specific interfaces, especially for packet sockets.
```lua
local sys_sock = require "posix.sys.socket"
ifindex, errmsg, errnum = sys_sock.if_nametoindex("eth0")
```
--------------------------------
### Get File Information with lstat
Source: https://luaposix.github.io/luaposix/modules/posix.sys.stat.html
Obtain file status information using `lstat`, which returns information about a symbolic link itself rather than the file it points to. Iterates through the returned `PosixStat` table.
```lua
local sys_stat = require "posix.sys.stat"
for a, b in pairs (sys_stat.lstat "/etc/") do print (a, b) end
```
--------------------------------
### Execute Program with exec
Source: https://luaposix.github.io/luaposix/modules/posix.unistd.html
Execute a program located at a specific path with the exec function. It takes the program path and a table of arguments, including index 0 for the program name.
```lua
exec ("/bin/bash", {[0] = "-sh", "--norc"})
```
--------------------------------
### Print Supported Stdio Constants
Source: https://luaposix.github.io/luaposix/modules/posix.stdio.html
Iterate through the `posix.stdio` module to print all available standard I/O constants that are supported on the current host system. Only numeric values are considered constants.
```lua
-- Print stdio constants supported on this host.
for name, value in pairs (require "posix.stdio") do
if type (value) == "number" then
print (name, value)
end
end
```
--------------------------------
### Get File Descriptor from Lua File Object
Source: https://luaposix.github.io/luaposix/modules/posix.stdio.html
Use `fileno` to retrieve the underlying file descriptor for a given Lua file object. This is useful for passing file descriptors to other POSIX functions that expect them.
```lua
local stdio = require "posix.stdio"
local unistd = require "posix.unistd"
assert (stdio.fileno (io.stdout) == unistd.STDOUT_FILENO)
```
--------------------------------
### connect
Source: https://luaposix.github.io/luaposix/modules/posix.sys.socket.html
Initiates a connection on a socket. This function is used by a client to establish a connection to a server at a specified address.
```APIDOC
## connect
### Description
Initiate a connection on a socket.
### Parameters
#### Path Parameters
- **fd** (number) - Required - The file descriptor of the socket.
- **addr** (table) - Required - The address structure of the server to connect to.
### Returns
- (boolean) - True on success.
```
--------------------------------
### Print Supported Resource Constants
Source: https://luaposix.github.io/luaposix/modules/posix.sys.resource.html
Iterates through the posix.sys.resource module and prints all supported resource limit constants and their numerical values. This is useful for discovering available limits on the host system.
```lua
-- Print resource constants supported on this host.
for name, value in pairs (require "posix.sys.resource") do
if type (value) == "number" then
print (name, value)
end
end
```
--------------------------------
### Listen for Netlink Uevents
Source: https://luaposix.github.io/luaposix/examples/netlink-uevent.lua.html
This snippet shows how to set up a netlink socket to receive kernel uevents. It requires the posix.sys.socket and posix.unistd modules. The socket is bound to the AF_NETLINK family with the process ID and all multicast groups.
```lua
#! /usr/bin/env lua
local M = require 'posix.sys.socket'
if M.AF_NETLINK ~= nil then
local getpid = require 'posix.unistd'.getpid
local fd, err = M.socket(M.AF_NETLINK, M.SOCK_DGRAM, M.NETLINK_KOBJECT_UEVENT)
assert(fd, err)
local ok, err = M.bind(fd, {family=M.AF_NETLINK, pid=getpid(), groups=-1})
assert(ok, err)
while true do
local data, err = M.recv(fd, 16384)
assert(data, err)
for k, v in string.gmatch(data, '%z(%u+)=([^%z]+)') do
print(k, v)
end
print '\n'
end
end
```
--------------------------------
### execx (task, ...)
Source: https://luaposix.github.io/luaposix/modules/posix.html
Executes a command or a Lua function. If a table or function is provided as the `task`, it can be used with `posix.unistd.execp` or as a Lua function that reads from standard input and writes to standard output.
```APIDOC
## execx (task, ...)
### Description
Executes a command or a Lua function. If a table or function is provided as the `task`, it can be used with `posix.unistd.execp` or as a Lua function that reads from standard input and writes to standard output.
### Parameters:
* `task` - A table or function. If a table, it's an argument list for `posix.unistd.execp`. If a function, it should read from standard input, write to standard output, and return an exit code.
* `...` - Positional arguments to be passed to the Lua function if `task` is a function.
### Returns:
* `nil`, `string` - Returns `nil` and an error message string on error. This function normally does not return on success.
```