title: ioctl_xfs_inumbers(2)

text:
# ioctl_xfs_inumbers(2)

## NAME
ioctl_xfs_inumbers - query allocation information for groups of XFS inodes

## SYNOPSIS
\#include <xfs/xfs_fs.h>

int ioctl(int fd, XFS_IOC_INUMBERS, struct xfs_inumbers_req *arg);

## DESCRIPTION
Query inode allocation information for groups of XFS inodes. This ioctl uses struct xfs_inumbers_req to set up a bulk transfer from the kernel:

```
struct xfs_inumbers_req {
	struct xfs_bulk_ireq    hdr;
	struct xfs_inumbers     inumbers[];
};
```

See below for the xfs_inumbers structure definition.

```
struct xfs_bulk_ireq {
	uint64_t                ino;
	uint32_t                flags;
	uint32_t                icount;
	uint32_t                ocount;
	uint32_t                agno;
	uint64_t                reserved[5];
};
```

hdr describes the information to query. The layout and behavior are documented in the ioctl_xfs_bulkstat(2) manpage and will not be discussed further here.

inumbers is an array of struct xfs_inumbers which is described below. The array must have at least icount elements.

```
struct xfs_inumbers {
	uint64_t                xi_startino;
	uint64_t                xi_allocmask;
	uint8_t                 xi_alloccount;
	uint8_t                 xi_version;
	uint8_t                 xi_padding[6];
};
```

This structure describes inode usage information for a group of 64 consecutive inode numbers.

xi_startino is the first inode number of this group.

xi_allocmask is a bitmask telling which inodes in this group are allocated. To clarify, bit N is set if inode xi_startino+N is allocated.

xi_alloccount is the number of inodes in this group that are allocated. This should be equal to popcnt(xi_allocmask).

xi_version is the version of this data structure. This will be set to XFS_INUMBERS_VERSION_V5 by the kernel.

xi_padding[6] is zeroed.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EFAULT

The kernel was not able to copy into the userspace buffer.

EFSBADCRC

Metadata checksum validation failed while performing the query.

EFSCORRUPTED

Metadata corruption was encountered while performing the query.

EINVAL

One of the arguments was not valid.

EIO

An I/O error was encountered while performing the query.

ENOMEM

There was insufficient memory to perform the query.

## CONFORMING TO
This API is specific to XFS filesystem on the Linux kernel.

## SEE ALSO
ioctl(2), ioctl_xfs_bulkstat(2).


package: libxfs-devel

title: ioctl_xfs_rtgroup_geometry(2)

text:
# ioctl_xfs_rtgroup_geometry(2)

## NAME
ioctl_xfs_rtgroup_geometry - query XFS realtime group geometry information

## SYNOPSIS
\#include <xfs/xfs_fs.h>

int ioctl(int fd, XFS_IOC_RTGROUP_GEOMETRY, struct xfs_rtgroup_geometry *arg);

## DESCRIPTION
This XFS ioctl retrieves the geometry information for a given realtime group. The geometry information is conveyed in a structure of the following form:

```
struct xfs_rtgroup_geometry {
	__u32  rg_number;
	__u32  rg_length;
	__u32  rg_sick;
	__u32  rg_checked;
	__u32  rg_flags;
	__u32  rg_reserved[27];
};
```

rg_number

The caller must set this field to the index of the realtime group that the caller wishes to learn about.

rg_length

The length of the realtime group is returned in this field, in units of filesystem blocks. rg_flags The caller can set this field to change the operational behavior of the ioctl. Currently no flags are defined, so this field must be zero.

rg_reserved and rg_pad

All reserved fields will be set to zero on return.

The fields rg_sick and rg_checked indicate the relative health of various realtime group metadata:

•

If a given sick flag is set in rg_sick, then that piece of metadata has been observed to be damaged. The same bit will be set in rg_checked.

•

If a given sick flag is set in rg_checked and is not set in rg_sick, then that piece of metadata has been checked and is not faulty.

•

If a given sick flag is not set in rg_checked, then no conclusion can be made.

The following flags apply to these fields:

XFS_RTGROUP_GEOM_SICK_SUPER

Realtime group superblock.

XFS_RTGROUP_GEOM_SICK_BITMAP

Realtime bitmap for this group.

XFS_RTGROUP_GEOM_SICK_SUMMARY

Realtime summary for this group.

XFS_RTGROUP_GEOM_SICK_RTRMAPBT

Reverse mapping btree for this group.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EFSBADCRC

Metadata checksum validation failed while performing the query.

EFSCORRUPTED

Metadata corruption was encountered while performing the query.

EINVAL

The specified realtime group number is not valid for this filesystem.

EIO

An I/O error was encountered while performing the query.

## CONFORMING TO
This API is specific to XFS filesystem on the Linux kernel.

## SEE ALSO
ioctl(2)

branch: sisyphus


title: ioctl_xfs_scrub_metadata(2)

summary: check XFS filesystem metadata

text:
# ioctl_xfs_scrub_metadata(2)

## NAME
ioctl_xfs_scrub_metadata - check XFS filesystem metadata

## SYNOPSIS
\#include <xfs/xfs_fs.h>

int ioctl(int dest_fd, XFS_IOC_SCRUB_METADATA, struct xfs_scrub_metadata *arg);

## DESCRIPTION
This XFS ioctl asks the kernel driver to examine a piece of filesystem metadata for errors or suboptimal metadata. Examination includes running metadata verifiers, checking records for obviously incorrect or impossible values, and cross-referencing each record with any other available metadata in the filesystem. This ioctl can also try to repair or optimize metadata, though this may block normal filesystem operations for a long period of time. The type and location of the metadata to scrub is conveyed in a structure of the following form:

```
struct xfs_scrub_metadata {
	__u32 sm_type;
	__u32 sm_flags;
	__u64 sm_ino;
	__u32 sm_gen;
	__u32 sm_agno;
	__u64 sm_reserved[5];
};
```

The field sm_reserved must be zero.

The field sm_type indicates the type of metadata to check:

XFS_SCRUB_TYPE_PROBE

Probe the kernel to see if it is willing to try to check or repair this filesystem. sm_agno, sm_ino, and sm_gen must be zero.

```
XFS_SCRUB_TYPE_SB
XFS_SCRUB_TYPE_AGF
XFS_SCRUB_TYPE_AGFL
```

XFS_SCRUB_TYPE_AGI

Examine a given allocation group's superblock, free space header, free block list, or inode header, respectively. Headers are checked for obviously incorrect values and cross-referenced against the allocation group's metadata btrees, if possible. The allocation group number must be given in sm_agno. sm_ino and sm_gen must be zero.

```
XFS_SCRUB_TYPE_BNOBT
XFS_SCRUB_TYPE_CNTBT
XFS_SCRUB_TYPE_INOBT
XFS_SCRUB_TYPE_FINOBT
XFS_SCRUB_TYPE_RMAPBT
```

XFS_SCRUB_TYPE_REFCNTBT

Examine a given allocation group's two free space btrees, two inode btrees, reverse mapping btrees, or reference count btrees, respectively. Records are checked for obviously incorrect values and cross-referenced with other allocation group metadata records to ensure that there are no conflicts. The allocation group number must be given in sm_agno. sm_ino and sm_gen must be zero.

XFS_SCRUB_TYPE_RGSUPER

Examine a given realtime allocation group's superblock. The realtime allocation group number must be given in sm_agno. sm_ino and sm_gen must be zero.

XFS_SCRUB_TYPE_INODE

Examine a given inode record for obviously incorrect values and discrepancies with the rest of filesystem metadata. Parent pointers are checked for impossible inode values and are then followed up to the parent directory to ensure that the linkage is correct. The inode to examine may be specified either through sm_ino and sm_gen; if not specified, then the file described by dest_fd will be examined. sm_agno must be zero.

```
XFS_SCRUB_TYPE_BMBTD
XFS_SCRUB_TYPE_BMBTA
```

XFS_SCRUB_TYPE_BMBTC

Examine a given inode's data block map, extended attribute block map, or copy on write block map. Inode records are examined for obviously incorrect values and discrepancies with the three block map types. The block maps are checked for obviously wrong values and cross-referenced with the allocation group space extent metadata for discrepancies. The inode to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

XFS_SCRUB_TYPE_XATTR

Examine the extended attribute records and indices of a given inode for incorrect pointers and other signs of damage. The inode to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

XFS_SCRUB_TYPE_DIR

Examine the entries in a given directory for invalid data or dangling pointers. If the filesystem supports directory parent pointers, each entry will be checked to confirm that the child file has a matching parent pointer. The directory to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

XFS_SCRUB_TYPE_PARENT

For filesystems that support directory parent pointers, this scrubber examines all the parent pointers attached to a file and confirms that the parent directory has an entry matching the parent pointer. For filesystems that do not support directory parent pointers, this scrubber checks that a subdirectory's dotdot entry points to a directory with an entry that points back to the subdirectory. The inode to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

XFS_SCRUB_TYPE_DIRTREE

This scrubber looks for problems in the directory tree structure such as loops and directories accessible through more than one path. Problems are detected by walking parent pointers upwards towards the root. Loops are detected by comparing the parent directory at each step against the directories already examined. Directories with multiple paths are detected by counting the parent pointers attached to a directory. Non-directories do not have links pointing away from the directory tree root and can be skipped. The directory to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

XFS_SCRUB_TYPE_SYMLINK

Examine the target of a symbolic link for obvious pathname problems. The link to examine can be specified in the same manner as XFS_SCRUB_TYPE_INODE.

```
XFS_SCRUB_TYPE_RTBITMAP
XFS_SCRUB_TYPE_RTSUM
XFS_SCRUB_TYPE_RTRMAPBT
```

XFS_SCRUB_TYPE_RTREFCBT

Examine a given realtime allocation group's free space bitmap, summary file, reverse mapping btree, or reference count btree, respectively.

```
XFS_SCRUB_TYPE_UQUOTA
XFS_SCRUB_TYPE_GQUOTA
```

XFS_SCRUB_TYPE_PQUOTA

Examine all user, group, or project quota records for corruption.

XFS_SCRUB_TYPE_FSCOUNTERS

Examine all filesystem summary counters (free blocks, inode count, free inode count) for errors.

XFS_SCRUB_TYPE_NLINKS

Scan all inodes in the filesystem to verify each file's link count.

XFS_SCRUB_TYPE_HEALTHY

Mark everything healthy after a clean scrub run. This clears out all the indirect health problem markers that might remain in the system.

XFS_SCRUB_TYPE_METAPATH

Check that a metadata directory path actually points to the active metadata inode. Metadata inodes are usually cached for the duration of the mount, so this scrubber ensures that the same inode will still be reachable after an unmount and mount cycle. Discrepancies can happen if the directory or parent pointer scrubbers rebuild a metadata directory but lose a link in the process. The sm_ino field should be passed one of the following special values to communicate which path to check:

XFS_SCRUB_METAPATH_RTDIR

Realtime metadata file subdirectory.

XFS_SCRUB_METAPATH_RTBITMAP

Realtime bitmap file.

XFS_SCRUB_METAPATH_RTSUMMARY

Realtime summary file.

XFS_SCRUB_METAPATH_QUOTADIR

Quota metadata file subdirectory.

XFS_SCRUB_METAPATH_USRQUOTA

User quota file.

XFS_SCRUB_METAPATH_GRPQUOTA

Group quota file.

XFS_SCRUB_METAPATH_PRJQUOTA

Project quota file.

XFS_SCRUB_METAPATH_RTRMAPBT

Realtime rmap btree file.

XFS_SCRUB_METAPATH_RTREFCOUNTBT

Realtime reference count btree file.

The values of sm_agno and sm_gen must be zero.

The field sm_flags control the behavior of the scrub operation and provide more information about the outcome of the operation. If none of the XFS_SCRUB_OFLAG_* flags are set upon return, the metadata is clean.

XFS_SCRUB_IFLAG_REPAIR

If the caller sets this flag, the kernel driver will examine the metadata and try to fix all problems and to optimize metadata when possible. If no errors occur during the repair operation, the check is performed a second time to determine whether the repair succeeded. If errors occur, the call returns an error status immediately.

XFS_SCRUB_OFLAG_CORRUPT

The metadata was corrupt when the call returned. If XFS_SCRUB_IFLAG_REPAIR was specified, then an attempted repair failed to fix the problem. Unmount the filesystem and run xfs_repair to fix the filesystem.

XFS_SCRUB_OFLAG_PREEN

The metadata is ok, but some aspect of the metadata could be optimized to increase performance. Call again with XFS_SCRUB_IFLAG_REPAIR to optimize the metadata.

XFS_SCRUB_OFLAG_XFAIL

Filesystem errors were encountered when accessing other metadata to cross-reference the records attached to this metadata object.

XFS_SCRUB_OFLAG_XCORRUPT

Discrepancies were found when cross-referencing the records attached to this metadata object against all other available metadata in the system.

XFS_SCRUB_OFLAG_INCOMPLETE

The checker was unable to complete its check of all records.

XFS_SCRUB_OFLAG_WARNING

The checker encountered a metadata object with potentially problematic records. However, the records were not obviously corrupt.

For metadata checkers that operate on inodes or inode metadata, the fields sm_ino and sm_gen are the inode number and generation number of the inode to check. If the inode number is zero, the inode represented by dest_fd is used instead. If the generation number of the inode does not match sm_gen, the call will return an error code for the invalid argument. The sm_agno field must be zero.

For metadata checkers that operate on allocation group metadata, the field sm_agno indicates the allocation group in which to find the metadata. The sm_ino and sm_gen fields must be zero.

For metadata checkers that operate on filesystem-wide metadata, no further arguments are required. sm_agno, sm_ino, and sm_gen must all be zero.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EBUSY

The filesystem object is busy; the operation will have to be tried again.

EFSCORRUPTED

Severe filesystem corruption was detected and could not be repaired. Unmount the filesystem and run xfs_repair to fix the filesystem.

EINVAL

One or more of the arguments specified is invalid.

ENOENT

The specified metadata object does not exist. For example, this error code is returned for a XFS_SCRUB_TYPE_REFCNTBT request on a filesystem that does not support reflink.

ENOMEM

There was not sufficient memory to perform the scrub or repair operation. Some operations (most notably reference count checking) require large amounts of memory.

ENOSPC

There is not enough free disk space to attempt a repair.

ENOTRECOVERABLE

Filesystem was mounted in norecovery mode and therefore has an unclean log. Neither scrub nor repair operations can be attempted with an unclean log.

ENOTTY

Online scrubbing or repair were not enabled.

EOPNOTSUPP

Repairs of the requested metadata object are not supported.

EROFS

Filesystem is read-only and a repair was requested.

ESHUTDOWN

Filesystem is shut down due to previous errors.

## CONFORMING TO
This API is specific to XFS filesystem on the Linux kernel.

## NOTES
These operations may block other filesystem operations for a long time. A calling process can stop the operation by being sent a fatal signal, but non-fatal signals are blocked.

## SEE ALSO
ioctl(2) xfs_scrub(8) xfs_repair(8)


title: ioctl_xfs_scrubv_metadata(2)

summary: check a lot of XFS filesystem metadata

text:
# ioctl_xfs_scrubv_metadata(2)

## NAME
ioctl_xfs_scrubv_metadata - check a lot of XFS filesystem metadata

## SYNOPSIS
\#include <xfs/xfs_fs.h>

int ioctl(int dest_fd, XFS_IOC_SCRUBV_METADATA, struct xfs_scrub_vec_head *arg);

## DESCRIPTION
This XFS ioctl asks the kernel driver to examine several pieces of filesystem metadata for errors or suboptimal metadata. Multiple scrub types can be invoked to target a single filesystem object. See ioctl_xfs_scrub_metadata(2) for a discussion of metadata validation, and documentation of the various XFS_SCRUB_TYPE and XFS_SCRUB_FLAGS values referenced below.

The types and location of the metadata to scrub are conveyed as a vector with a header of the following form:

```
struct xfs_scrub_vec_head {
	__u64 svh_ino;
	__u32 svh_gen;
	__u32 svh_agno;
	__u32 svh_flags;
	__u16 svh_rest_us;
	__u16 svh_nr;
	__u64 svh_reserved;
	__u64 svh_vectors;
};
```

The field svh_ino, svh_gen, and svh_agno correspond to the sm_ino, sm_gen, and sm_agno fields of the regular scrub ioctl. Exactly one filesystem object can be specified in a single call. The kernel will proceed with each vector in svh_vectors until progress is no longer possible.

The field svh_rest_us specifies an amount of time to pause between each scrub invocation to give the system a chance to process other requests.

The field svh_nr specifies the number of vectors in the svh_vectors array.

The field svh_vectors is a pointer to an array of struct xfs_scrub_vec structures.

The field svh_reserved must be zero.

Each vector has the following form:

```
struct xfs_scrub_vec {
	__u32 sv_type;
	__u32 sv_flags;
	__s32 sv_ret;
	__u32 sv_reserved;
};
```

The fields sv_type and sv_flags indicate the type of metadata to check and the behavioral changes that userspace will permit of the kernel. The sv_flags field will be updated upon completion of the scrub call. See the documentation of XFS_SCRUB_TYPE_* and XFS_SCRUB_[IO]FLAG_* values in ioctl_xfs_scrub_metadata(2) for a detailed description of their purpose.

If a vector's sv_type field is set to the value XFS_SCRUB_TYPE_BARRIER, the kernel will stop processing vectors and return to userspace if a scrubber flags corruption by setting one of the XFS_SCRUB_OFLAG_* values in sv_flags or returns an operation error in sv_ret. Otherwise, the kernel returns only after processing all vectors.

The sv_ret field is set to the return value of the scrub function. See the RETURN VALUE section of the ioctl_xfs_scrub_metadata(2) manual page for more information.

The sv_reserved field must be zero.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EINVAL

One or more of the arguments specified is invalid.

EINTR

The operation was interrupted.

ENOMEM

There was not sufficient memory to perform the scrub or repair operation.

EFAULT

A memory fault was encountered while reading or writing the vector.

## CONFORMING TO
This API is specific to XFS filesystem on the Linux kernel.

## NOTES
These operations may block other filesystem operations for a long time. A calling process can stop the operation by being sent a fatal signal, but non-fatal signals are blocked.

## SEE ALSO
ioctl(2) ioctl_xfs_scrub_metadata(2) xfs_scrub(8) xfs_repair(8)


title: ioctl_xfs_verify_media(2)

text:
# ioctl_xfs_verify_media(2)

## NAME
ioctl_xfs_verify_media - verify the media of the devices backing XFS

## SYNOPSIS
\#include <xfs/xfs_fs.h>

int ioctl(int fd, XFS_IOC_VERIFY_MEDIA, struct xfs_verify_media *arg);

## DESCRIPTION
Verify the media of a storage device backing an XFS filesystem. If errors are found, report the error to the kernel so that it can generate health events for the health monitoring system and fsnotify. The verification request is conveyed in a structure of the following form:

```
struct xfs_verify_media {
	__u32	me_dev;
	__u32	me_flags;
	__u64	me_start_daddr;
	__u64	me_end_daddr;
	__u32	me_ioerror;
	__u32	me_max_io_size;
	__u32	me_rest_us;
	__u32	me_pad;
};
```

The field me_pad must be zero.

The field me_ioerror will be set if the ioctl returns success.

The fields me_start_daddr and me_end_daddr are the range of the storage device to verify. Both values must be in units of 512-byte blocks. The me_start_daddr field is inclusive, and the me_end_daddr field is exclusive. If me_end_daddr is larger than the size of the device, the kernel will set it to the size of the device.

If the system call returns success and any part of the storage device range was successfully verified, the me_start_daddr field will be updated to reflect the successful verification. If after this update the me_start_daddr is equal to me_end_daddr, then the entire range was verified successfully.

If not, then a media error was encountered and the caller should generate a series of secondary calls to this ioctl with smaller ranges to discover the exact location and type of media error. The type of media error will be written to the me_ioerror field.

The me_max_io_size field, if nonzero, is an upper bound on the I/O operations that the kernel will issue to the block device.

The me_rest_us is the time duration, in microseconds, for which the kernel will wait between issuing I/O operations.

The field me_dev must be one of the following values:

XFS_DEV_DATA

Verify the data device.

XFS_DEV_LOG

Verify the external log device.

XFS_DEV_RT

Verify the realtime device.

The field me_flags is a bitmask of one of the following values:

XFS_VERIFY_MEDIA_REPORT

Report all media errors to fsnotify.

The me_max_io_size field, if nonzero, will be used as advice for the maximum size of the IO to send to the device.

The me_rest_us field will cause the kernel to pause for this many microseconds between IO requests.

## RETURN VALUE
On runtime error, -1 is returned, and errno is set to indicate the error. If 0 is returned, then start_daddr or ioerror will be updated.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EPERM

The calling process does not have sufficient privilege.

EINVAL

One or more of the arguments specified is invalid.

EFAULT

The arg structure could not be copied into the kernel.

ENODEV

The device is not present.

ENOMEM

There was not enough memory to perform the verification.

## I/O ERRORS
The ioerror field could be set to one of the following:

0

The verification I/O succeeded.

EOPNOTSUPP

ETIMEDOUT

The kernel timed out the verification I/O command.

ENOLINK

The transportation link to the storage device was down temporarily.

EREMOTEIO

The storage target controller suffered a critical error.

ENODATA

The storage target media suffered a critical error.

EILSEQ

Storage protection metadata did not validate successfully.

ENOMEM

There was not enough memory to allocate an I/O request.

ENODEV

The storage device is offline.

ETIME

The storage device timed out the I/O command.

EINVAL

The I/O request was rejected by the device for being invalid.

EIO

An I/O error occurred but no specific details are available.

This list is not exhaustive and may grow in the future.

## CONFORMING TO
This API is specific to XFS filesystem on the Linux kernel.

## SEE ALSO
ioctl_xfs_health_monitor(2)


package: man-pages

title: _exit(2)

summary: terminate the calling process

text:
# _exit(2)

## NAME
_exit, _Exit - terminate the calling process

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
[[noreturn]] void _exit(int status);
```

```
#include <stdlib.h>
```

```
[[noreturn]] void _Exit(int status);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

_Exit():

```
    _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
```

## DESCRIPTION
_exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed. Any children of the process are inherited by init(1) (or by the nearest "subreaper" process as defined through the use of the prctl(2) PR_SET_CHILD_SUBREAPER operation). The process's parent is sent a SIGCHLD signal.

The value status & 0xFF is returned to the parent process as the process's exit status, and can be collected by the parent using one of the wait(2) family of calls.

The function _Exit() is equivalent to _exit().

## RETURN VALUE
These functions do not return.

## STANDARDS
_exit()

POSIX.1-2008.

_Exit()

C11, POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.3BSD.

_Exit() was introduced by C99.

## NOTES
For a discussion on the effects of an exit, the transmission of exit status, zombie processes, signals sent, and so on, see exit(3).

The function _exit() is like exit(3), but does not call any functions registered with atexit(3) or on_exit(3). Open stdio(3) streams are not flushed. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish. If the delay is undesired, it may be useful to call functions like tcflush(3) before calling _exit(). Whether any pending I/O is canceled, and which pending I/O may be canceled upon _exit(), is implementation-dependent.

### C library/kernel differences
The text above in DESCRIPTION describes the traditional effect of _exit(), which is to terminate a process, and these are the semantics specified by POSIX.1 and implemented by the C library wrapper function. On modern systems, this means termination of all threads in the process.

By contrast with the C library wrapper function, the raw Linux _exit() system call terminates only the calling thread, and actions such as reparenting child processes or sending SIGCHLD to the parent process are performed only if this is the last thread in the thread group.

Up to glibc 2.3, the _exit() wrapper function invoked the kernel system call of the same name. Since glibc 2.3, the wrapper function invokes exit_group(2), in order to terminate all of the threads in a process.

## SEE ALSO
execve(2), exit_group(2), fork(2), kill(2), wait(2), wait4(2), waitpid(2), atexit(3), exit(3), on_exit(3), termios(3)


title: _syscall(2)

text:
# _syscall(2)

## NAME
_syscall - invoking a system call without library support (OBSOLETE)

## SYNOPSIS

```
#include <linux/unistd.h>
```

```
A _syscall macro
```

```
desired system call
```

## DESCRIPTION
The important thing to know about a system call is its prototype. You need to know how many arguments, their types, and the function return type. There are seven macros that make the actual call into the system easier. They have the form:

```
_syscallX(type,name,type1,arg1,type2,arg2,...)
```

where

X is 0–6, which are the number of arguments taken by the system call

type is the return type of the system call

name is the name of the system call

typeN is the Nth argument's type

argN is the name of the Nth argument

These macros create a function called name with the arguments you specify. Once you include the _syscall() in your source file, you call the system call by name.

## FILES
/usr/include/linux/unistd.h

## STANDARDS
Linux.

## HISTORY
Starting around Linux 2.6.18, the _syscall macros were removed from header files supplied to user space. Use syscall(2) instead. (Some architectures, notably ia64, never provided the _syscall macros; on those architectures, syscall(2) was always required.)

## NOTES
The _syscall() macros do not produce a prototype. You may have to create one, especially for C++ users.

System calls are not required to return only positive or negative error codes. You need to read the source to be sure how it will return errors. Usually, it is the negative of a standard error code, for example, -EPERM. The _syscall() macros will return the result r of the system call when r is nonnegative, but will return -1 and set the variable errno to -r when r is negative. For the error codes, see errno(3).

When defining a system call, the argument types must be passed by-value or by-pointer (for aggregates like structs).

## EXAMPLES

```
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <linux/unistd.h>       /* for _syscallX macros/related stuff */
#include <linux/kernel.h>       /* for struct sysinfo */
_syscall1(int, sysinfo, struct sysinfo *, info);
int
main(void)
{

    struct sysinfo s_info;

    int error;

    error = sysinfo(&s_info);

    printf("code error = %d\n", error);

    printf("Uptime = %lds\nLoad: 1 min %lu / 5 min %lu / 15 min %lu\n"

           "RAM: total %lu / free %lu / shared %lu\n"

           "Memory in buffers = %lu\nSwap: total %lu / free %lu\n"

           "Number of processes = %d\n",

           s_info.uptime, s_info.loads[0],

           s_info.loads[1], s_info.loads[2],

           s_info.totalram, s_info.freeram,

           s_info.sharedram, s_info.bufferram,

           s_info.totalswap, s_info.freeswap,

           s_info.procs);

    exit(EXIT_SUCCESS);
}
```

### Sample output

```
code error = 0
uptime = 502034s
Load: 1 min 13376 / 5 min 5504 / 15 min 1152
RAM: total 15343616 / free 827392 / shared 8237056
Memory in buffers = 5066752
Swap: total 27881472 / free 24698880
Number of processes = 40
```

## SEE ALSO
intro(2), syscall(2), errno(3)


accept

title: accept(2)

summary: accept a connection on a socket

text:
# accept(2)

## NAME
accept, accept4 - accept a connection on a socket

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/socket.h>
```

```
int accept(int sockfd, struct sockaddr *_Nullable restrict addr,
           socklen_t *_Nullable restrict addrlen);
```

```
#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <sys/socket.h>
```

```
int accept4(int sockfd, struct sockaddr *_Nullable restrict addr,
           socklen_t *_Nullable restrict addrlen, int flags);
```

## DESCRIPTION
The accept() system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call.

The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2).

The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL.

The addrlen argument is a value-result argument: the caller must initialize it to contain the size (in bytes) of the structure pointed to by addr; on return it will contain the actual size of the peer address.

The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.

If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept() blocks the caller until a connection is present. If the socket is marked nonblocking and no pending connections are present on the queue, accept() fails with the error EAGAIN or EWOULDBLOCK.

In order to be notified of incoming connections on a socket, you can use select(2), poll(2), or epoll(7). A readable event will be delivered when a new connection is attempted and you may then call accept() to get a socket for that connection. Alternatively, you can set the socket to deliver SIGIO when activity occurs on a socket; see socket(7) for details.

If flags is 0, then accept4() is the same as accept(). The following values can be bitwise ORed in flags to obtain different behavior:

SOCK_NONBLOCK

Set the O_NONBLOCK file status flag on the open file description (see open(2)) referred to by the new file descriptor. Using this flag saves extra calls to fcntl(2) to achieve the same result.

SOCK_CLOEXEC

Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful.

## RETURN VALUE
On success, these system calls return a file descriptor for the accepted socket (a nonnegative integer). On error, -1 is returned, errno is set to indicate the error, and addrlen is left unchanged.

### Error handling
Linux accept() (and accept4()) passes already-pending network errors on the new socket as an error code from accept(). This behavior differs from other BSD socket implementations. For reliable operation the application should detect the network errors defined for the protocol after accept() and treat them like EAGAIN by retrying. In the case of TCP/IP, these are ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH.

## ERRORS
EAGAIN or EWOULDBLOCK

The socket is marked nonblocking and no connections are present to be accepted. POSIX.1-2001 and POSIX.1-2008 allow either error to be returned for this case, and do not require these constants to have the same value, so a portable application should check for both possibilities.

EBADF

sockfd is not an open file descriptor.

ECONNABORTED

A connection has been aborted.

EFAULT

The addr argument is not in a writable part of the user address space.

EINTR

The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).

EINVAL

Socket is not listening for connections, or addrlen is invalid (e.g., is negative).

EINVAL

(accept4()) invalid value in flags.

EMFILE

The per-process limit on the number of open file descriptors has been reached.

ENFILE

The system-wide limit on the total number of open files has been reached.

ENOBUFS, ENOMEM

Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

EOPNOTSUPP

The referenced socket is not of type SOCK_STREAM.

EPERM

Firewall rules forbid connection.

EPROTO

Protocol error.

In addition, network errors for the new socket and as defined for the protocol may be returned. Various Linux kernels can return other errors such as ENOSR, ESOCKTNOSUPPORT, EPROTONOSUPPORT, ETIMEDOUT. The value ERESTARTSYS may be seen during a trace.

## VERSIONS
On Linux, the new socket returned by accept() does not inherit file status flags such as O_NONBLOCK and O_ASYNC from the listening socket. This behavior differs from the canonical BSD sockets implementation. Portable programs should not rely on inheritance or noninheritance of file status flags and always explicitly set all required flags on the socket returned from accept().

## STANDARDS
accept()

POSIX.1-2008.

accept4()

Linux.

## HISTORY
accept()

POSIX.1-2001, SVr4, 4.4BSD (accept() first appeared in 4.2BSD).

accept4()

Linux 2.6.28, glibc 2.10.

## NOTES
There may not always be a connection waiting after a SIGIO is delivered or select(2), poll(2), or epoll(7) return a readability event because the connection might have been removed by an asynchronous network error or another thread before accept() is called. If this happens, then the call will block waiting for the next connection to arrive. To ensure that accept() never blocks, the passed socket sockfd needs to have the O_NONBLOCK flag set (see socket(7)).

For certain protocols which require an explicit confirmation, such as DECnet, accept() can be thought of as merely dequeuing the next connection request and not implying confirmation. Confirmation can be implied by a normal read or write on the new file descriptor, and rejection can be implied by closing the new socket. Currently, only DECnet has these semantics on Linux.

### The socklen_t type
In the original BSD sockets implementation (and on other older systems) the third argument of accept() was declared as an int *. A POSIX.1g draft standard wanted to change it into a size_t *C; later POSIX standards and glibc 2.x have socklen_t * .

## EXAMPLES
See bind(2).

## SEE ALSO
bind(2), connect(2), listen(2), select(2), socket(2), socket(7)


access

title: access(2)

summary: check user's permissions for a file

text:
# access(2)

## NAME
access, faccessat, faccessat2 - check user's permissions for a file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
int access(const char *pathname, int mode);
```

```
#include <fcntl.h>            /* Definition of AT_* constants */
#include <unistd.h>
```

```
int faccessat(int dirfd, const char *pathname, int mode, int flags);

                /* But see C library/kernel differences, below */
```

```
#include <fcntl.h>            /* Definition of AT_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_faccessat2,
            int dirfd, const char *pathname, int mode, int flags);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

faccessat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
access() checks whether the calling process can access the file pathname. If pathname is a symbolic link, it is dereferenced.

The mode specifies the accessibility check(s) to be performed, and is either the value F_OK, or a mask consisting of the bitwise OR of one or more of R_OK, W_OK, and X_OK. F_OK tests for the existence of the file. R_OK, W_OK, and X_OK test whether the file exists and grants read, write, and execute permissions, respectively.

The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. Similarly, for the root user, the check uses the set of permitted capabilities rather than the set of effective capabilities; and for non-root users, the check uses an empty set of capabilities.

This allows set-user-ID programs and capability-endowed programs to easily determine the invoking user's authority. In other words, access() does not answer the "can I read/write/execute this file?" question. It answers a slightly different question: "(assuming I'm a setuid binary) can the user who invoked me read/write/execute this file?", which gives set-user-ID programs the possibility to prevent malicious users from causing them to read files which users shouldn't be able to read.

If the calling process is privileged (i.e., its real UID is zero), then an X_OK check is successful for a regular file if execute permission is enabled for any of the file owner, group, or other.

### faccessat()
faccessat() operates in exactly the same way as access(), except for the differences described here.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by access() for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like access()).

If pathname is absolute, then dirfd is ignored.

flags is constructed by ORing together zero or more of the following values:

AT_EACCESS

Perform access checks using the effective user and group IDs. By default, faccessat() uses the real IDs (like access()).

AT_SYMLINK_NOFOLLOW

If pathname is a symbolic link, do not dereference it: instead return information about the link itself.

See openat(2) for an explanation of the need for faccessat().

### faccessat2()
The description of faccessat() given above corresponds to POSIX.1 and to the implementation provided by glibc. However, the glibc implementation was an imperfect emulation (see BUGS) that papered over the fact that the raw Linux faccessat() system call does not have a flags argument. To allow for a proper implementation, Linux 5.8 added the faccessat2() system call, which supports the flags argument and allows a correct implementation of the faccessat() wrapper function.

## RETURN VALUE
On success (all requested permissions granted, or mode is F_OK and the file exists), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or mode is F_OK and the file does not exist, or some other error occurred), -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).)

EBADF

(faccessat()) pathname is relative but dirfd is neither AT_FDCWD (faccessat()) nor a valid file descriptor.

EFAULT

pathname points outside your accessible address space.

EINVAL

mode was incorrectly specified.

EINVAL

(faccessat()) Invalid flag specified in flags.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

pathname is too long.

ENOENT

A component of pathname does not exist or is a dangling symbolic link.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component used as a directory in pathname is not, in fact, a directory.

ENOTDIR

(faccessat()) pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

EPERM

Write permission was requested to a file that has the immutable flag set. See also ioctl_iflags(2).

EROFS

Write permission was requested for a file on a read-only filesystem.

ETXTBSY

Write access was requested to an executable which is being executed.

## VERSIONS
If the calling process has appropriate privileges (i.e., is superuser), POSIX.1-2001 permits an implementation to indicate success for an X_OK check even if none of the execute file permission bits are set. Linux does not do this.

### C library/kernel differences
The raw faccessat() system call takes only the first three arguments. The AT_EACCESS and AT_SYMLINK_NOFOLLOW flags are actually implemented within the glibc wrapper function for faccessat(). If either of these flags is specified, then the wrapper function employs fstatat(2) to determine access permissions, but see BUGS.

### glibc notes
On older kernels where faccessat() is unavailable (and when the AT_EACCESS and AT_SYMLINK_NOFOLLOW flags are not specified), the glibc wrapper function falls back to the use of access(). When pathname is a relative pathname, glibc constructs a pathname based on the symbolic link in /proc/self/fd that corresponds to the dirfd argument.

## STANDARDS
access()

faccessat()

POSIX.1-2008.

faccessat2()

Linux.

## HISTORY
access()

SVr4, 4.3BSD, POSIX.1-2001.

faccessat()

Linux 2.6.16, glibc 2.4.

faccessat2()

Linux 5.8.

## NOTES
Warning: Using these calls to check if a user is authorized to, for example, open a file before actually doing so using open(2) creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. For this reason, the use of this system call should be avoided. (In the example just described, a safer alternative would be to temporarily switch the process's effective user ID to the real ID and then call open(2).)

access() always dereferences symbolic links. If you need to check the permissions on a symbolic link, use faccessat() with the flag AT_SYMLINK_NOFOLLOW.

These calls return an error if any of the access types in mode is denied, even if some of the other access types in mode are permitted.

A file is accessible only if the permissions on each of the directories in the path prefix of pathname grant search (i.e., execute) access. If any directory is inaccessible, then the access() call fails, regardless of the permissions on the file itself.

Only access bits are checked, not the file type or contents. Therefore, if a directory is found to be writable, it probably means that files can be created in the directory, and not that the directory can be written as a file. Similarly, a DOS file may be reported as executable, but the execve(2) call will still fail.

These calls may not work correctly on NFSv2 filesystems with UID mapping enabled, because UID mapping is done on the server and hidden from the client, which checks permissions. (NFS versions 3 and higher perform the check on the server.) Similar problems can occur to FUSE mounts.

## BUGS
Because the Linux kernel's faccessat() system call does not support a flags argument, the glibc faccessat() wrapper function provided in glibc 2.32 and earlier emulates the required functionality using a combination of the faccessat() system call and fstatat(2). However, this emulation does not take ACLs into account. Starting with glibc 2.33, the wrapper function avoids this bug by making use of the faccessat2() system call where it is provided by the underlying kernel.

In Linux 2.4 (and earlier) there is some strangeness in the handling of X_OK tests for superuser. If all categories of execute permission are disabled for a nondirectory file, then the only access() test that returns -1 is when mode is specified as just X_OK; if R_OK or W_OK is also specified in mode, then access() returns 0 for such files. Early Linux 2.6 (up to and including Linux 2.6.3) also behaved in the same way as Linux 2.4.

Before Linux 2.6.20, these calls ignored the effect of the MS_NOEXEC flag if it was used to mount(2) the underlying filesystem. Since Linux 2.6.20, the MS_NOEXEC flag is honored.

## SEE ALSO
chmod(2), chown(2), open(2), setgid(2), setuid(2), stat(2), euidaccess(3), credentials(7), path_resolution(7), symlink(7)


acct

title: acct(2)

summary: switch process accounting on or off

text:
# acct(2)

## NAME
acct - switch process accounting on or off

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
int acct(const char *_Nullable filename);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

acct():

```
    Since glibc 2.21:

        _DEFAULT_SOURCE

    In glibc 2.19 and 2.20:

        _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

    Up to and including glibc 2.19:

        _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
```

## DESCRIPTION
The acct() system call enables or disables process accounting. If called with the name of an existing file as its argument, accounting is turned on, and records for each terminating process are appended to filename as it terminates. An argument of NULL causes accounting to be turned off.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

Write permission is denied for the specified file, or search permission is denied for one of the directories in the path prefix of filename (see also path_resolution(7)), or filename is not a regular file.

EFAULT

filename points outside your accessible address space.

EIO

Error writing to the file filename.

EISDIR

filename is a directory.

ELOOP

Too many symbolic links were encountered in resolving filename.

ENAMETOOLONG

filename was too long.

ENFILE

The system-wide limit on the total number of open files has been reached.

ENOENT

The specified file does not exist.

ENOMEM

Out of memory.

ENOSYS

BSD process accounting has not been enabled when the operating system kernel was compiled. The kernel configuration parameter controlling this feature is CONFIG_BSD_PROCESS_ACCT.

ENOTDIR

A component used as a directory in filename is not in fact a directory.

EPERM

The calling process has insufficient privilege to enable process accounting. On Linux, the CAP_SYS_PACCT capability is required.

EROFS

filename refers to a file on a read-only filesystem.

EUSERS

There are no more free file structures or we ran out of memory.

## STANDARDS
None.

## HISTORY
SVr4, 4.3BSD.

## NOTES
No accounting is produced for programs running when a system crash occurs. In particular, nonterminating processes are never accounted for.

The structure of the records written to the accounting file is described in acct(5).

## SEE ALSO
acct(5)


title: add_key(2)

text:
# add_key(2)

## NAME
add_key - add a key to the kernel's key management facility

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <keyutils.h>
```

```
key_serial_t add_key(const char *type, const char *description,
                     const void payload[.plen], size_t plen,
                     key_serial_t keyring);
```

Note: There is no glibc wrapper for this system call; see NOTES.

## DESCRIPTION
add_key() creates or updates a key of the given type and description, instantiates it with the payload of length plen, attaches it to the nominated keyring, and returns the key's serial number.

The key may be rejected if the provided data is in the wrong format or it is invalid in some other way.

If the destination keyring already contains a key that matches the specified type and description, then, if the key type supports it, that key will be updated rather than a new key being created; if not, a new key (with a different ID) will be created and it will displace the link to the extant key from the keyring.

The destination keyring serial number may be that of a valid keyring for which the caller has write permission. Alternatively, it may be one of the following special keyring IDs:

KEY_SPEC_THREAD_KEYRING

This specifies the caller's thread-specific keyring (thread-keyring(7)).

KEY_SPEC_PROCESS_KEYRING

This specifies the caller's process-specific keyring (process-keyring(7)).

KEY_SPEC_SESSION_KEYRING

This specifies the caller's session-specific keyring (session-keyring(7)).

KEY_SPEC_USER_KEYRING

This specifies the caller's UID-specific keyring (user-keyring(7)).

KEY_SPEC_USER_SESSION_KEYRING

This specifies the caller's UID-session keyring (user-session-keyring(7)).

### Key types
The key type is a string that specifies the key's type. Internally, the kernel defines a number of key types that are available in the core key management code. Among the types that are available for user-space use and can be specified as the type argument to add_key() are the following:

"keyring"

Keyrings are special key types that may contain links to sequences of other keys of any type. If this interface is used to create a keyring, then payload should be NULL and plen should be zero.

"user"

This is a general purpose key type whose payload may be read and updated by user-space applications. The key is kept entirely within kernel memory. The payload for keys of this type is a blob of arbitrary data of up to 32,767 bytes.

"logon" (since Linux 3.3)

This key type is essentially the same as "user", but it does not permit the key to read. This is suitable for storing payloads that you do not want to be readable from user space.

This key type vets the description to ensure that it is qualified by a "service" prefix, by checking to ensure that the description contains a ':' that is preceded by other characters.

"big_key" (since Linux 3.13)

This key type is similar to "user", but may hold a payload of up to 1 MiB. If the key payload is large enough, then it may be stored encrypted in tmpfs (which can be swapped out) rather than kernel memory.

For further details on these key types, see keyrings(7).

## RETURN VALUE
On success, add_key() returns the serial number of the key it created or updated. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

The keyring wasn't available for modification by the user.

EDQUOT

The key quota for this user would be exceeded by creating this key or linking it to the keyring.

EFAULT

One or more of type, description, and payload points outside process's accessible address space.

EINVAL

The size of the string (including the terminating null byte) specified in type or description exceeded the limit (32 bytes and 4096 bytes respectively).

EINVAL

The payload data was invalid.

EINVAL

type was "logon" and the description was not qualified with a prefix string of the form "service:".

EKEYEXPIRED

The keyring has expired.

EKEYREVOKED

The keyring has been revoked.

ENOKEY

The keyring doesn't exist.

ENOMEM

Insufficient memory to create a key.

EPERM

The type started with a period ('.'). Key types that begin with a period are reserved to the implementation.

EPERM

type was "keyring" and the description started with a period ('.'). Keyrings with descriptions (names) that begin with a period are reserved to the implementation.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.10.

## NOTES
glibc does not provide a wrapper for this system call. A wrapper is provided in the libkeyutils library. (The accompanying package provides the <keyutils.h> header file.) When employing the wrapper in that library, link with -lkeyutils.

## EXAMPLES
The program below creates a key with the type, description, and payload specified in its command-line arguments, and links that key into the session keyring. The following shell session demonstrates the use of the program:

```
$ ./a.out user mykey "Some payload"
Key ID is 64a4dca
$ grep '64a4dca' /proc/keys
064a4dca I--Q---    1 perm 3f010000  1000  1000 user    mykey: 12
```

### Program source

```
#include <keyutils.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{

    key_serial_t key;

    if (argc != 4) {

        fprintf(stderr, "Usage: %s type description payload\n",

                argv[0]);

        exit(EXIT_FAILURE);

    }

    key = add_key(argv[1], argv[2], argv[3], strlen(argv[3]),

                  KEY_SPEC_SESSION_KEYRING);

    if (key == -1) {

        perror("add_key");

        exit(EXIT_FAILURE);

    }

    printf("Key ID is %jx\n", (uintmax_t) key);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
keyctl(1), keyctl(2), request_key(2), keyctl(3), keyrings(7), keyutils(7), persistent-keyring(7), process-keyring(7), session-keyring(7), thread-keyring(7), user-keyring(7), user-session-keyring(7)

The kernel source files Documentation/security/keys/core.rst and Documentation/keys/request-key.rst (or, before Linux 4.13, in the files Documentation/security/keys.txt and Documentation/security/keys-request-key.txt).


adjtimex

title: adjtimex(2)

summary: tune kernel clock

text:
# adjtimex(2)

## NAME
adjtimex, clock_adjtime, ntp_adjtime - tune kernel clock

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/timex.h>
```

```
int adjtimex(struct timex *buf);
```

```
int clock_adjtime(clockid_t clk_id, struct timex *buf);
```

```
int ntp_adjtime(struct timex *buf);
```

## DESCRIPTION
Linux uses David L. Mills' clock adjustment algorithm (see RFC 5905). The system call adjtimex() reads and optionally sets adjustment parameters for this algorithm. It takes a pointer to a timex structure, updates kernel parameters from (selected) field values, and returns the same structure updated with the current kernel values. This structure is declared as follows:

```
struct timex {

    int  modes;      /* Mode selector */

    long offset;     /* Time offset; nanoseconds, if STA_NANO

                        status flag is set, otherwise

                        microseconds */

    long freq;       /* Frequency offset; see NOTES for units */

    long maxerror;   /* Maximum error (microseconds) */

    long esterror;   /* Estimated error (microseconds) */

    int  status;     /* Clock command/status */

    long constant;   /* PLL (phase-locked loop) time constant */

    long precision;  /* Clock precision

                        (microseconds, read-only) */

    long tolerance;  /* Clock frequency tolerance (read-only);

                        see NOTES for units */

    struct timeval time;

                     /* Current time (read-only, except for

                        ADJ_SETOFFSET); upon return, time.tv_usec

                        contains nanoseconds, if STA_NANO status

                        flag is set, otherwise microseconds */

    long tick;       /* Microseconds between clock ticks */

    long ppsfreq;    /* PPS (pulse per second) frequency

                        (read-only); see NOTES for units */

    long jitter;     /* PPS jitter (read-only); nanoseconds, if

                        STA_NANO status flag is set, otherwise

                        microseconds */

    int  shift;      /* PPS interval duration

                        (seconds, read-only) */

    long stabil;     /* PPS stability (read-only);

                        see NOTES for units */

    long jitcnt;     /* PPS count of jitter limit exceeded

                        events (read-only) */

    long calcnt;     /* PPS count of calibration intervals

                        (read-only) */

    long errcnt;     /* PPS count of calibration errors

                        (read-only) */

    long stbcnt;     /* PPS count of stability limit exceeded

                        events (read-only) */

    int tai;         /* TAI offset, as set by previous ADJ_TAI

                        operation (seconds, read-only,

                        since Linux 2.6.26) */

    /* Further padding bytes to allow for future expansion */
};
```

The modes field determines which parameters, if any, to set. (As described later in this page, the constants used for ntp_adjtime() are equivalent but differently named.) It is a bit mask containing a bitwise OR combination of zero or more of the following bits:

ADJ_OFFSET

Set time offset from buf.offset. Since Linux 2.6.26, the supplied value is clamped to the range (-0.5s, +0.5s). In older kernels, an EINVAL error occurs if the supplied value is out of range.

ADJ_FREQUENCY

Set frequency offset from buf.freq. Since Linux 2.6.26, the supplied value is clamped to the range (-32768000, +32768000). In older kernels, an EINVAL error occurs if the supplied value is out of range.

ADJ_MAXERROR

Set maximum time error from buf.maxerror.

ADJ_ESTERROR

Set estimated time error from buf.esterror.

ADJ_STATUS

Set clock status bits from buf.status. A description of these bits is provided below.

ADJ_TIMECONST

Set PLL time constant from buf.constant. If the STA_NANO status flag (see below) is clear, the kernel adds 4 to this value.

ADJ_SETOFFSET (since Linux 2.6.39)

Add buf.time to the current time. If buf.status includes the ADJ_NANO flag, then buf.time.tv_usec is interpreted as a nanosecond value; otherwise it is interpreted as microseconds.

The value of buf.time is the sum of its two fields, but the field buf.time.tv_usec must always be nonnegative. The following example shows how to normalize a timeval with nanosecond resolution.

```
while (buf.time.tv_usec < 0) {

    buf.time.tv_sec  -= 1;

    buf.time.tv_usec += 1000000000;
}

```

ADJ_MICRO (since Linux 2.6.26)

Select microsecond resolution.

ADJ_NANO (since Linux 2.6.26)

Select nanosecond resolution. Only one of ADJ_MICRO and ADJ_NANO should be specified.

ADJ_TAI (since Linux 2.6.26)

Set TAI (Atomic International Time) offset from buf.constant.

ADJ_TAI should not be used in conjunction with ADJ_TIMECONST, since the latter mode also employs the buf.constant field.

For a complete explanation of TAI and the difference between TAI and UTC, see BIPM

ADJ_TICK

Set tick value from buf.tick.

Alternatively, modes can be specified as either of the following (multibit mask) values, in which case other bits should not be specified in modes:

ADJ_OFFSET_SINGLESHOT

Old-fashioned adjtime(3): (gradually) adjust time by value specified in buf.offset, which specifies an adjustment in microseconds.

ADJ_OFFSET_SS_READ (functional since Linux 2.6.28)

Return (in buf.offset) the remaining amount of time to be adjusted after an earlier ADJ_OFFSET_SINGLESHOT operation. This feature was added in Linux 2.6.24, but did not work correctly until Linux 2.6.28.

Ordinary users are restricted to a value of either 0 or ADJ_OFFSET_SS_READ for modes. Only the superuser may set any parameters.

The buf.status field is a bit mask that is used to set and/or retrieve status bits associated with the NTP implementation. Some bits in the mask are both readable and settable, while others are read-only.

STA_PLL (read-write)

Enable phase-locked loop (PLL) updates via ADJ_OFFSET.

STA_PPSFREQ (read-write)

Enable PPS (pulse-per-second) frequency discipline.

STA_PPSTIME (read-write)

Enable PPS time discipline.

STA_FLL (read-write)

Select frequency-locked loop (FLL) mode.

STA_INS (read-write)

Insert a leap second after the last second of the UTC day, thus extending the last minute of the day by one second. Leap-second insertion will occur each day, so long as this flag remains set.

STA_DEL (read-write)

Delete a leap second at the last second of the UTC day. Leap second deletion will occur each day, so long as this flag remains set.

STA_UNSYNC (read-write)

Clock unsynchronized.

STA_FREQHOLD (read-write)

Hold frequency. Normally adjustments made via ADJ_OFFSET result in dampened frequency adjustments also being made. So a single call corrects the current offset, but as offsets in the same direction are made repeatedly, the small frequency adjustments will accumulate to fix the long-term skew.

This flag prevents the small frequency adjustment from being made when correcting for an ADJ_OFFSET value.

STA_PPSSIGNAL (read-only)

A valid PPS (pulse-per-second) signal is present.

STA_PPSJITTER (read-only)

PPS signal jitter exceeded.

STA_PPSWANDER (read-only)

PPS signal wander exceeded.

STA_PPSERROR (read-only)

PPS signal calibration error.

STA_CLOCKERR (read-only)

Clock hardware fault.

STA_NANO (read-only; since Linux 2.6.26)

Resolution (0 = microsecond, 1 = nanoseconds). Set via ADJ_NANO, cleared via ADJ_MICRO.

STA_MODE (since Linux 2.6.26)

Mode (0 = Phase Locked Loop, 1 = Frequency Locked Loop).

STA_CLK (read-only; since Linux 2.6.26)

Clock source (0 = A, 1 = B); currently unused.

Attempts to set read-only status bits are silently ignored.

### clock_adjtime ()
The clock_adjtime() system call (added in Linux 2.6.39) behaves like adjtimex() but takes an additional clk_id argument to specify the particular clock on which to act.

### ntp_adjtime ()
The ntp_adjtime() library function (described in the NTP "Kernel Application Program API", KAPI) is a more portable interface for performing the same task as adjtimex(). Other than the following points, it is identical to adjtimex():

•

The constants used in modes are prefixed with "MOD_" rather than "ADJ_", and have the same suffixes (thus, MOD_OFFSET, MOD_FREQUENCY, and so on), other than the exceptions noted in the following points.

•

MOD_CLKA is the synonym for ADJ_OFFSET_SINGLESHOT.

•

MOD_CLKB is the synonym for ADJ_TICK.

•

The is no synonym for ADJ_OFFSET_SS_READ, which is not described in the KAPI.

## RETURN VALUE
On success, adjtimex() and ntp_adjtime() return the clock state; that is, one of the following values:

TIME_OK

Clock synchronized, no leap second adjustment pending.

TIME_INS

Indicates that a leap second will be added at the end of the UTC day.

TIME_DEL

Indicates that a leap second will be deleted at the end of the UTC day.

TIME_OOP

Insertion of a leap second is in progress.

TIME_WAIT

A leap-second insertion or deletion has been completed. This value will be returned until the next ADJ_STATUS operation clears the STA_INS and STA_DEL flags.

TIME_ERROR

The system clock is not synchronized to a reliable server. This value is returned when any of the following holds true:

•

Either STA_UNSYNC or STA_CLOCKERR is set.

•

STA_PPSSIGNAL is clear and either STA_PPSFREQ or STA_PPSTIME is set.

•

STA_PPSTIME and STA_PPSJITTER are both set.

•

STA_PPSFREQ is set and either STA_PPSWANDER or STA_PPSJITTER is set.

The symbolic name TIME_BAD is a synonym for TIME_ERROR, provided for backward compatibility.

Note that starting with Linux 3.4, the call operates asynchronously and the return value usually will not reflect a state change caused by the call itself.

On failure, these calls return -1 and set errno to indicate the error.

## ERRORS
EFAULT

buf does not point to writable memory.

EINVAL (before Linux 2.6.26)

An attempt was made to set buf.freq to a value outside the range (-33554432, +33554432).

EINVAL (before Linux 2.6.26)

An attempt was made to set buf.offset to a value outside the permitted range. Before Linux 2.0, the permitted range was (-131072, +131072). From Linux 2.0 onwards, the permitted range was (-512000, +512000).

EINVAL

An attempt was made to set buf.status to a value other than those listed above.

EINVAL

The clk_id given to clock_adjtime() is invalid for one of two reasons. Either the System-V style hard-coded positive clock ID value is out of range, or the dynamic clk_id does not refer to a valid instance of a clock object. See clock_gettime(2) for a discussion of dynamic clocks.

EINVAL

An attempt was made to set buf.tick to a value outside the range 900000/HZ to 1100000/HZ, where HZ is the system timer interrupt frequency.

ENODEV

The hot-pluggable device (like USB for example) represented by a dynamic clk_id has disappeared after its character device was opened. See clock_gettime(2) for a discussion of dynamic clocks.

EOPNOTSUPP

The given clk_id does not support adjustment.

EPERM

buf.modes is neither 0 nor ADJ_OFFSET_SS_READ, and the caller does not have sufficient privilege. Under Linux, the CAP_SYS_TIME capability is required.

## ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).

Interface

Attribute

Value

ntp_adjtime ()

Thread safety

MT-Safe

## STANDARDS
adjtimex()

clock_adjtime()

Linux.

The preferred API for the NTP daemon is ntp_adjtime().

## NOTES
In struct timex, freq, ppsfreq, and stabil are ppm (parts per million) with a 16-bit fractional part, which means that a value of 1 in one of those fields actually means 2^-16 ppm, and 2^16=65536 is 1 ppm. This is the case for both input values (in the case of freq) and output values.

The leap-second processing triggered by STA_INS and STA_DEL is done by the kernel in timer context. Thus, it will take one tick into the second for the leap second to be inserted or deleted.

## SEE ALSO
clock_gettime(2), clock_settime(2), settimeofday(2), adjtime(3), ntp_gettime(3), capabilities(7), time(7), adjtimex(8), hwclock(8)

NTP "Kernel Application Program Interface"


alarm

title: alarm(2)

text:
# alarm(2)

## NAME
alarm - set an alarm clock for delivery of a signal

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
unsigned int alarm(unsigned int seconds);
```

## DESCRIPTION
alarm() arranges for a SIGALRM signal to be delivered to the calling process in seconds seconds.

If seconds is zero, any pending alarm is canceled.

In any event any previously set alarm() is canceled.

## RETURN VALUE
alarm() returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.3BSD.

## NOTES
alarm() and setitimer(2) share the same timer; calls to one will interfere with use of the other.

Alarms created by alarm() are preserved across execve(2) and are not inherited by children created via fork(2).

sleep(3) may be implemented using SIGALRM; mixing calls to alarm() and sleep(3) is a bad idea.

Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.

## SEE ALSO
gettimeofday(2), pause(2), select(2), setitimer(2), sigaction(2), signal(2), timer_create(2), timerfd_create(2), sleep(3), time(7)


title: alloc_hugepages(2)

summary: allocate or free huge pages

text:
# alloc_hugepages(2)

## NAME
alloc_hugepages, free_hugepages - allocate or free huge pages

## SYNOPSIS

```
void *syscall(SYS_alloc_hugepages, int key, void addr[.len], size_t len,
              int prot, int flag);
int syscall(SYS_free_hugepages, void *addr);
```

Note: glibc provides no wrappers for these system calls, necessitating the use of syscall(2).

## DESCRIPTION
The system calls alloc_hugepages() and free_hugepages() were introduced in Linux 2.5.36 and removed again in Linux 2.5.54. They existed only on i386 and ia64 (when built with CONFIG_HUGETLB_PAGE). In Linux 2.4.20, the syscall numbers exist, but the calls fail with the error ENOSYS.

On i386 the memory management hardware knows about ordinary pages (4 KiB) and huge pages (2 or 4 MiB). Similarly ia64 knows about huge pages of several sizes. These system calls serve to map huge pages into the process's memory or to free them again. Huge pages are locked into memory, and are not swapped.

The key argument is an identifier. When zero the pages are private, and not inherited by children. When positive the pages are shared with other applications using the same key, and inherited by child processes.

The addr argument of free_hugepages() tells which page is being freed: it was the return value of a call to alloc_hugepages(). (The memory is first actually freed when all users have released it.) The addr argument of alloc_hugepages() is a hint, that the kernel may or may not follow. Addresses must be properly aligned.

The len argument is the length of the required segment. It must be a multiple of the huge page size.

The prot argument specifies the memory protection of the segment. It is one of PROT_READ, PROT_WRITE, PROT_EXEC.

The flag argument is ignored, unless key is positive. In that case, if flag is IPC_CREAT, then a new huge page segment is created when none with the given key existed. If this flag is not set, then ENOENT is returned when no segment with the given key exists.

## RETURN VALUE
On success, alloc_hugepages() returns the allocated virtual address, and free_hugepages() returns zero. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
ENOSYS

The system call is not supported on this kernel.

## FILES
/proc/sys/vm/nr_hugepages

Number of configured hugetlb pages. This can be read and written.

/proc/meminfo

Gives info on the number of configured hugetlb pages and on their size in the three variables HugePages_Total, HugePages_Free, Hugepagesize.

## STANDARDS
Linux on Intel processors.

## HISTORY
These system calls are gone; they existed only in Linux 2.5.36 through to Linux 2.5.54.

## NOTES
Now the hugetlbfs filesystem can be used instead. Memory backed by huge pages (if the CPU supports them) is obtained by using mmap(2) to map files in this virtual filesystem.

The maximal number of huge pages can be specified using the hugepages= boot parameter.


title: arch_prctl(2)

summary: set architecture-specific thread state

text:
# arch_prctl(2)

## NAME
arch_prctl - set architecture-specific thread state

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <asm/prctl.h>        /* Definition of ARCH_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_arch_prctl, int code, unsigned long addr);
int syscall(SYS_arch_prctl, int code, unsigned long *addr);
```

Note: glibc provides no wrapper for arch_prctl(), necessitating the use of syscall(2).

## DESCRIPTION
arch_prctl() sets architecture-specific process or thread state. code selects a subfunction and passes argument addr to it; addr is interpreted as either an unsigned long for the "set" operations, or as an unsigned long *, for the "get" operations.

Subfunctions for both x86 and x86-64 are:

ARCH_SET_CPUID (since Linux 4.12)

Enable (addr != 0) or disable (addr == 0) the cpuid instruction for the calling thread. The instruction is enabled by default. If disabled, any execution of a cpuid instruction will instead generate a SIGSEGV signal. This feature can be used to emulate cpuid results that differ from what the underlying hardware would have produced (e.g., in a paravirtualization setting).

The ARCH_SET_CPUID setting is preserved across fork(2) and clone(2) but reset to the default (i.e., cpuid enabled) on execve(2).

ARCH_GET_CPUID (since Linux 4.12)

Return the setting of the flag manipulated by ARCH_SET_CPUID as the result of the system call (1 for enabled, 0 for disabled). addr is ignored.

Subfunctions for x86-64 only are:

ARCH_SET_FS

Set the 64-bit base for the FS register to addr.

ARCH_GET_FS

Return the 64-bit base value for the FS register of the calling thread in the unsigned long pointed to by addr.

ARCH_SET_GS

Set the 64-bit base for the GS register to addr.

ARCH_GET_GS

Return the 64-bit base value for the GS register of the calling thread in the unsigned long pointed to by addr.

## RETURN VALUE
On success, arch_prctl() returns 0; on error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

addr points to an unmapped address or is outside the process address space.

EINVAL

code is not a valid subcommand.

ENODEV

ARCH_SET_CPUID was requested, but the underlying hardware does not support CPUID faulting.

EPERM

addr is outside the process address space.

## STANDARDS
Linux/x86-64.

## NOTES
arch_prctl() is supported only on Linux/x86-64 for 64-bit programs currently.

The 64-bit base changes when a new 32-bit segment selector is loaded.

ARCH_SET_GS is disabled in some kernels.

Context switches for 64-bit segment bases are rather expensive. As an optimization, if a 32-bit TLS base address is used, arch_prctl() may use a real TLS entry as if set_thread_area(2) had been called, instead of manipulating the segment base register directly. Memory in the first 2 GB of address space can be allocated by using mmap(2) with the MAP_32BIT flag.

Because of the aforementioned optimization, using arch_prctl() and set_thread_area(2) in the same thread is dangerous, as they may overwrite each other's TLS entries.

FS may be already used by the threading library. Programs that use ARCH_SET_FS directly are very likely to crash.

## SEE ALSO
mmap(2), modify_ldt(2), prctl(2), set_thread_area(2)

AMD X86-64 Programmer's manual


bdflush

title: bdflush(2)

text:
# bdflush(2)

## NAME
bdflush - start, flush, or tune buffer-dirty-flush daemon

## SYNOPSIS

```
#include <sys/kdaemon.h>
```

```
[[deprecated]] int bdflush(int func, long *address);
[[deprecated]] int bdflush(int func, long data);
```

## DESCRIPTION
Note: Since Linux 2.6, this system call is deprecated and does nothing. It is likely to disappear altogether in a future kernel release. Nowadays, the task performed by bdflush() is handled by the kernel pdflush thread.

bdflush() starts, flushes, or tunes the buffer-dirty-flush daemon. Only a privileged process (one with the CAP_SYS_ADMIN capability) may call bdflush().

If func is negative or 0, and no daemon has been started, then bdflush() enters the daemon code and never returns.

If func is 1, some dirty buffers are written to disk.

If func is 2 or more and is even (low bit is 0), then address is the address of a long word, and the tuning parameter numbered (func-2)/2 is returned to the caller in that address.

If func is 3 or more and is odd (low bit is 1), then data is a long word, and the kernel sets tuning parameter numbered (func-3)/2 to that value.

The set of parameters, their values, and their valid ranges are defined in the Linux kernel source file fs/buffer.c.

## RETURN VALUE
If func is negative or 0 and the daemon successfully starts, bdflush() never returns. Otherwise, the return value is 0 on success and -1 on failure, with errno set to indicate the error.

## ERRORS
EBUSY

An attempt was made to enter the daemon code after another process has already entered.

EFAULT

address points outside your accessible address space.

EINVAL

An attempt was made to read or write an invalid parameter number, or to write an invalid value to a parameter.

EPERM

Caller does not have the CAP_SYS_ADMIN capability.

## STANDARDS
Linux.

## HISTORY
Since glibc 2.23, glibc no longer supports this obsolete system call.

## SEE ALSO
sync(1), fsync(2), sync(2)


bind

title: bind(2)

summary: bind a name to a socket

text:
# bind(2)

## NAME
bind - bind a name to a socket

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/socket.h>
```

```
int bind(int sockfd, const struct sockaddr *addr,
         socklen_t addrlen);
```

## DESCRIPTION
When a socket is created with socket(2), it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called “assigning a name to a socket”.

It is normally necessary to assign a local address using bind() before a SOCK_STREAM socket may receive connections (see accept(2)).

The rules used in name binding vary between address families. Consult the manual entries in Section 7 for detailed information. For AF_INET, see ip(7); for AF_INET6, see ipv6(7); for AF_UNIX, see unix(7); for AF_APPLETALK, see ddp(7); for AF_PACKET, see packet(7); for AF_X25, see x25(7); and for AF_NETLINK, see netlink(7).

The actual structure passed for the addr argument will depend on the address family. The sockaddr structure is defined as something like:

```
struct sockaddr {

    sa_family_t sa_family;

    char        sa_data[14];
}
```

The only purpose of this structure is to cast the structure pointer passed in addr in order to avoid compiler warnings. See EXAMPLES below.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

The address is protected, and the user is not the superuser.

EADDRINUSE

The given address is already in use.

EADDRINUSE

(Internet domain sockets) The port number was specified as zero in the socket address structure, but, upon attempting to bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).

EBADF

sockfd is not a valid file descriptor.

EINVAL

The socket is already bound to an address.

EINVAL

addrlen is wrong, or addr is not a valid address for this socket's domain.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

The following errors are specific to UNIX domain (AF_UNIX) sockets:

EACCES

Search permission is denied on a component of the path prefix. (See also path_resolution(7).)

EADDRNOTAVAIL

A nonexistent interface was requested or the requested address was not local.

EFAULT

addr points outside the user's accessible address space.

ELOOP

Too many symbolic links were encountered in resolving addr.

ENAMETOOLONG

addr is too long.

ENOENT

A component in the directory prefix of the socket pathname does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of the path prefix is not a directory.

EROFS

The socket inode would reside on a read-only filesystem.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.4BSD (bind() first appeared in 4.2BSD).

## BUGS
The transparent proxy options are not described.

## EXAMPLES
An example of the use of bind() with Internet domain sockets can be found in getaddrinfo(3).

The following example shows how to bind a stream socket in the UNIX (AF_UNIX) domain, and accept connections:

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define MY_SOCK_PATH "/somepath"
#define LISTEN_BACKLOG 50
#define handle_error(msg) \

    do { perror(msg); exit(EXIT_FAILURE); } while (0)
int
main(void)
{

    int                 sfd, cfd;

    socklen_t           peer_addr_size;

    struct sockaddr_un  my_addr, peer_addr;

    sfd = socket(AF_UNIX, SOCK_STREAM, 0);

    if (sfd == -1)

        handle_error("socket");

    memset(&my_addr, 0, sizeof(my_addr));

    my_addr.sun_family = AF_UNIX;

    strncpy(my_addr.sun_path, MY_SOCK_PATH,

            sizeof(my_addr.sun_path) - 1);

    if (bind(sfd, (struct sockaddr *) &my_addr,

             sizeof(my_addr)) == -1)

        handle_error("bind");

    if (listen(sfd, LISTEN_BACKLOG) == -1)

        handle_error("listen");

    /* Now we can accept incoming connections one

       at a time using accept(2). */

    peer_addr_size = sizeof(peer_addr);

    cfd = accept(sfd, (struct sockaddr *) &peer_addr,

                 &peer_addr_size);

    if (cfd == -1)

        handle_error("accept");

    /* Code to deal with incoming connection(s)... */

    if (close(sfd) == -1)

        handle_error("close");

    if (unlink(MY_SOCK_PATH) == -1)

        handle_error("unlink");
}
```

## SEE ALSO
accept(2), connect(2), getsockname(2), listen(2), socket(2), getaddrinfo(3), getifaddrs(3), ip(7), ipv6(7), path_resolution(7), socket(7), unix(7)