clone

title: clone(2)

summary: create a child process

text:
# clone(2)

## NAME
clone, __clone2, clone3 - create a child process

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

## SYNOPSIS

```
/* Prototype for the glibc wrapper function */
```

```
#define _GNU_SOURCE
#include <sched.h>
```

```
int clone(int (*fn)(void *_Nullable), void *stack, int flags,
          void *_Nullable arg, ...  /* pid_t *_Nullable parent_tid,
                                       void *_Nullable tls,
                                       pid_t *_Nullable child_tid */ );
```

```
/* For the prototype of the raw clone() system call, see NOTES */
```

```
#include <linux/sched.h>    /* Definition of struct clone_args */
#include <sched.h>          /* Definition of CLONE_* constants */
#include <sys/syscall.h>    /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_clone3, struct clone_args *cl_args, size_t size);
```

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

## DESCRIPTION
These system calls create a new ("child") process, in a manner similar to fork(2).

By contrast with fork(2), these system calls provide more precise control over what pieces of execution context are shared between the calling process and the child process. For example, using these system calls, the caller can control whether or not the two processes share the virtual address space, the table of file descriptors, and the table of signal handlers. These system calls also allow the new child process to be placed in separate namespaces(7).

Note that in this manual page, "calling process" normally corresponds to "parent process". But see the descriptions of CLONE_PARENT and CLONE_THREAD below.

This page describes the following interfaces:

•

The glibc clone() wrapper function and the underlying system call on which it is based. The main text describes the wrapper function; the differences for the raw system call are described toward the end of this page.

•

The newer clone3() system call.

In the remainder of this page, the terminology "the clone call" is used when noting details that apply to all of these interfaces,

### The clone() wrapper function
When the child process is created with the clone() wrapper function, it commences execution by calling the function pointed to by the argument fn. (This differs from fork(2), where execution continues in the child from the point of the fork(2) call.) The arg argument is passed as the argument of the function fn.

When the fn(arg) function returns, the child process terminates. The integer returned by fn is the exit status for the child process. The child process may also terminate explicitly by calling exit(2) or after receiving a fatal signal.

The stack argument specifies the location of the stack used by the child process. Since the child and calling process may share memory, it is not possible for the child process to execute in the same stack as the calling process. The calling process must therefore set up memory space for the child stack and pass a pointer to this space to clone(). Stacks grow downward on all processors that run Linux (except the HP PA processors), so stack usually points to the topmost address of the memory space set up for the child stack. Note that clone() does not provide a means whereby the caller can inform the kernel of the size of the stack area.

The remaining arguments to clone() are discussed below.

### clone3()
The clone3() system call provides a superset of the functionality of the older clone() interface. It also provides a number of API improvements, including: space for additional flags bits; cleaner separation in the use of various arguments; and the ability to specify the size of the child's stack area.

As with fork(2), clone3() returns in both the parent and the child. It returns 0 in the child process and returns the PID of the child in the parent.

The cl_args argument of clone3() is a structure of the following form:

```
struct clone_args {

    u64 flags;        /* Flags bit mask */

    u64 pidfd;        /* Where to store PID file descriptor

                         (int *) */

    u64 child_tid;    /* Where to store child TID,

                         in child's memory (pid_t *) */

    u64 parent_tid;   /* Where to store child TID,

                         in parent's memory (pid_t *) */

    u64 exit_signal;  /* Signal to deliver to parent on

                         child termination */

    u64 stack;        /* Pointer to lowest byte of stack */

    u64 stack_size;   /* Size of stack */

    u64 tls;          /* Location of new TLS */

    u64 set_tid;      /* Pointer to a pid_t array

                         (since Linux 5.5) */

    u64 set_tid_size; /* Number of elements in set_tid

                         (since Linux 5.5) */

    u64 cgroup;       /* File descriptor for target cgroup

                         of child (since Linux 5.7) */
};
```

The size argument that is supplied to clone3() should be initialized to the size of this structure. (The existence of the size argument permits future extensions to the clone_args structure.)

The stack for the child process is specified via cl_args.stack, which points to the lowest byte of the stack area, and cl_args.stack_size, which specifies the size of the stack in bytes. In the case where the CLONE_VM flag (see below) is specified, a stack must be explicitly allocated and specified. Otherwise, these two fields can be specified as NULL and 0, which causes the child to use the same stack area as the parent (in the child's own virtual address space).

The remaining fields in the cl_args argument are discussed below.

### Equivalence between clone() and clone3() arguments
Unlike the older clone() interface, where arguments are passed individually, in the newer clone3() interface the arguments are packaged into the clone_args structure shown above. This structure allows for a superset of the information passed via the clone() arguments.

The following table shows the equivalence between the arguments of clone() and the fields in the clone_args argument supplied to clone3():

clone()

clone3()

Notes

cl_args field

flags & ~0xff

flags

For most flags; details below

parent_tid

pidfd

See CLONE_PIDFD

child_tid

child_tid

See CLONE_CHILD_SETTID

parent_tid

parent_tid

See CLONE_PARENT_SETTID

flags & 0xff

exit_signal

stack

stack

---

stack_size

tls

tls

See CLONE_SETTLS

---

set_tid

See below for details

---

set_tid_size

---

cgroup

See CLONE_INTO_CGROUP

### The child termination signal
When the child process terminates, a signal may be sent to the parent. The termination signal is specified in the low byte of flags (clone()) or in cl_args.exit_signal (clone3()). If this signal is specified as anything other than SIGCHLD, then the parent process must specify the __WALL or __WCLONE options when waiting for the child with wait(2). If no signal (i.e., zero) is specified, then the parent process is not signaled when the child terminates.

### The set_tid array
By default, the kernel chooses the next sequential PID for the new process in each of the PID namespaces where it is present. When creating a process with clone3(), the set_tid array (available since Linux 5.5) can be used to select specific PIDs for the process in some or all of the PID namespaces where it is present. If the PID of the newly created process should be set only for the current PID namespace or in the newly created PID namespace (if flags contains CLONE_NEWPID) then the first element in the set_tid array has to be the desired PID and set_tid_size needs to be 1.

If the PID of the newly created process should have a certain value in multiple PID namespaces, then the set_tid array can have multiple entries. The first entry defines the PID in the most deeply nested PID namespace and each of the following entries contains the PID in the corresponding ancestor PID namespace. The number of PID namespaces in which a PID should be set is defined by set_tid_size which cannot be larger than the number of currently nested PID namespaces.

To create a process with the following PIDs in a PID namespace hierarchy:

PID NS level

Requested PID

Notes

0

31496

Outermost PID namespace

1

42

2

7

Innermost PID namespace

Set the array to:

```
set_tid[0] = 7;
set_tid[1] = 42;
set_tid[2] = 31496;
set_tid_size = 3;
```

If only the PIDs in the two innermost PID namespaces need to be specified, set the array to:

```
set_tid[0] = 7;
set_tid[1] = 42;
set_tid_size = 2;
```

The PID in the PID namespaces outside the two innermost PID namespaces is selected the same way as any other PID is selected.

The set_tid feature requires CAP_SYS_ADMIN or (since Linux 5.9) CAP_CHECKPOINT_RESTORE in all owning user namespaces of the target PID namespaces.

Callers may only choose a PID greater than 1 in a given PID namespace if an init process (i.e., a process with PID 1) already exists in that namespace. Otherwise the PID entry for this PID namespace must be 1.

### The flags mask
Both clone() and clone3() allow a flags bit mask that modifies their behavior and allows the caller to specify what is shared between the calling process and the child process. This bit mask—the flags argument of clone() or the cl_args.flags field passed to clone3()—is referred to as the flags mask in the remainder of this page.

The flags mask is specified as a bitwise OR of zero or more of the constants listed below. Except as noted below, these flags are available (and have the same effect) in both clone() and clone3().

CLONE_CHILD_CLEARTID (since Linux 2.5.49)

Clear (zero) the child thread ID at the location pointed to by child_tid (clone()) or cl_args.child_tid (clone3()) in child memory when the child exits, and do a wakeup on the futex at that address. The address involved may be changed by the set_tid_address(2) system call. This is used by threading libraries.

CLONE_CHILD_SETTID (since Linux 2.5.49)

Store the child thread ID at the location pointed to by child_tid (clone()) or cl_args.child_tid (clone3()) in the child's memory. The store operation completes before the clone call returns control to user space in the child process. (Note that the store operation may not have completed before the clone call returns in the parent process, which is relevant if the CLONE_VM flag is also employed.)

CLONE_CLEAR_SIGHAND (since Linux 5.5)

By default, signal dispositions in the child thread are the same as in the parent. If this flag is specified, then all signals that are handled in the parent are reset to their default dispositions (SIG_DFL) in the child.

Specifying this flag together with CLONE_SIGHAND is nonsensical and disallowed.

CLONE_DETACHED (historical)

For a while (during the Linux 2.5 development series) there was a CLONE_DETACHED flag, which caused the parent not to receive a signal when the child terminated. Ultimately, the effect of this flag was subsumed under the CLONE_THREAD flag and by the time Linux 2.6.0 was released, this flag had no effect. Starting in Linux 2.6.2, the need to give this flag together with CLONE_THREAD disappeared.

This flag is still defined, but it is usually ignored when calling clone(). However, see the description of CLONE_PIDFD for some exceptions.

CLONE_FILES (since Linux 2.0)

If CLONE_FILES is set, the calling process and the child process share the same file descriptor table. Any file descriptor created by the calling process or by the child process is also valid in the other process. Similarly, if one of the processes closes a file descriptor, or changes its associated flags (using the fcntl(2) F_SETFD operation), the other process is also affected. If a process sharing a file descriptor table calls execve(2), its file descriptor table is duplicated (unshared).

If CLONE_FILES is not set, the child process inherits a copy of all file descriptors opened in the calling process at the time of the clone call. Subsequent operations that open or close file descriptors, or change file descriptor flags, performed by either the calling process or the child process do not affect the other process. Note, however, that the duplicated file descriptors in the child refer to the same open file descriptions as the corresponding file descriptors in the calling process, and thus share file offsets and file status flags (see open(2)).

CLONE_FS (since Linux 2.0)

If CLONE_FS is set, the caller and the child process share the same filesystem information. This includes the root of the filesystem, the current working directory, and the umask. Any call to chroot(2), chdir(2), or umask(2) performed by the calling process or the child process also affects the other process.

If CLONE_FS is not set, the child process works on a copy of the filesystem information of the calling process at the time of the clone call. Calls to chroot(2), chdir(2), or umask(2) performed later by one of the processes do not affect the other process.

CLONE_INTO_CGROUP (since Linux 5.7)

By default, a child process is placed in the same version 2 cgroup as its parent. The CLONE_INTO_CGROUP flag allows the child process to be created in a different version 2 cgroup. (Note that CLONE_INTO_CGROUP has effect only for version 2 cgroups.)

In order to place the child process in a different cgroup, the caller specifies CLONE_INTO_CGROUP in cl_args.flags and passes a file descriptor that refers to a version 2 cgroup in the cl_args.cgroup field. (This file descriptor can be obtained by opening a cgroup v2 directory using either the O_RDONLY or the O_PATH flag.) Note that all of the usual restrictions (described in cgroups(7)) on placing a process into a version 2 cgroup apply.

Among the possible use cases for CLONE_INTO_CGROUP are the following:

•

Spawning a process into a cgroup different from the parent's cgroup makes it possible for a service manager to directly spawn new services into dedicated cgroups. This eliminates the accounting jitter that would be caused if the child process was first created in the same cgroup as the parent and then moved into the target cgroup. Furthermore, spawning the child process directly into a target cgroup is significantly cheaper than moving the child process into the target cgroup after it has been created.

•

The CLONE_INTO_CGROUP flag also allows the creation of frozen child processes by spawning them into a frozen cgroup. (See cgroups(7) for a description of the freezer controller.)

•

For threaded applications (or even thread implementations which make use of cgroups to limit individual threads), it is possible to establish a fixed cgroup layout before spawning each thread directly into its target cgroup.

CLONE_IO (since Linux 2.6.25)

If CLONE_IO is set, then the new process shares an I/O context with the calling process. If this flag is not set, then (as with fork(2)) the new process has its own I/O context.

The I/O context is the I/O scope of the disk scheduler (i.e., what the I/O scheduler uses to model scheduling of a process's I/O). If processes share the same I/O context, they are treated as one by the I/O scheduler. As a consequence, they get to share disk time. For some I/O schedulers, if two processes share an I/O context, they will be allowed to interleave their disk access. If several threads are doing I/O on behalf of the same process (aio_read(3), for instance), they should employ CLONE_IO to get better I/O performance.

If the kernel is not configured with the CONFIG_BLOCK option, this flag is a no-op.

CLONE_NEWCGROUP (since Linux 4.6)

Create the process in a new cgroup namespace. If this flag is not set, then (as with fork(2)) the process is created in the same cgroup namespaces as the calling process.

For further information on cgroup namespaces, see cgroup_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWCGROUP.

CLONE_NEWIPC (since Linux 2.6.19)

If CLONE_NEWIPC is set, then create the process in a new IPC namespace. If this flag is not set, then (as with fork(2)), the process is created in the same IPC namespace as the calling process.

For further information on IPC namespaces, see ipc_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWIPC. This flag can't be specified in conjunction with CLONE_SYSVSEM.

CLONE_NEWNET (since Linux 2.6.24)

(The implementation of this flag was completed only by about Linux 2.6.29.)

If CLONE_NEWNET is set, then create the process in a new network namespace. If this flag is not set, then (as with fork(2)) the process is created in the same network namespace as the calling process.

For further information on network namespaces, see network_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWNET.

CLONE_NEWNS (since Linux 2.4.19)

If CLONE_NEWNS is set, the cloned child is started in a new mount namespace, initialized with a copy of the namespace of the parent. If CLONE_NEWNS is not set, the child lives in the same mount namespace as the parent.

For further information on mount namespaces, see namespaces(7) and mount_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWNS. It is not permitted to specify both CLONE_NEWNS and CLONE_FS in the same clone call.

CLONE_NEWPID (since Linux 2.6.24)

If CLONE_NEWPID is set, then create the process in a new PID namespace. If this flag is not set, then (as with fork(2)) the process is created in the same PID namespace as the calling process.

For further information on PID namespaces, see namespaces(7) and pid_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWPID. This flag can't be specified in conjunction with CLONE_THREAD or CLONE_PARENT.

CLONE_NEWUSER

(This flag first became meaningful for clone() in Linux 2.6.23, the current clone() semantics were merged in Linux 3.5, and the final pieces to make the user namespaces completely usable were merged in Linux 3.8.)

If CLONE_NEWUSER is set, then create the process in a new user namespace. If this flag is not set, then (as with fork(2)) the process is created in the same user namespace as the calling process.

For further information on user namespaces, see namespaces(7) and user_namespaces(7).

Before Linux 3.8, use of CLONE_NEWUSER required that the caller have three capabilities: CAP_SYS_ADMIN, CAP_SETUID, and CAP_SETGID. Starting with Linux 3.8, no privileges are needed to create a user namespace.

This flag can't be specified in conjunction with CLONE_THREAD or CLONE_PARENT. For security reasons, CLONE_NEWUSER cannot be specified in conjunction with CLONE_FS.

CLONE_NEWUTS (since Linux 2.6.19)

If CLONE_NEWUTS is set, then create the process in a new UTS namespace, whose identifiers are initialized by duplicating the identifiers from the UTS namespace of the calling process. If this flag is not set, then (as with fork(2)) the process is created in the same UTS namespace as the calling process.

For further information on UTS namespaces, see uts_namespaces(7).

Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWUTS.

CLONE_PARENT (since Linux 2.3.12)

If CLONE_PARENT is set, then the parent of the new child (as returned by getppid(2)) will be the same as that of the calling process.

If CLONE_PARENT is not set, then (as with fork(2)) the child's parent is the calling process.

Note that it is the parent process, as returned by getppid(2), which is signaled when the child terminates, so that if CLONE_PARENT is set, then the parent of the calling process, rather than the calling process itself, is signaled.

The CLONE_PARENT flag can't be used in clone calls by the global init process (PID 1 in the initial PID namespace) and init processes in other PID namespaces. This restriction prevents the creation of multi-rooted process trees as well as the creation of unreapable zombies in the initial PID namespace.

CLONE_PARENT_SETTID (since Linux 2.5.49)

Store the child thread ID at the location pointed to by parent_tid (clone()) or cl_args.parent_tid (clone3()) in the parent's memory. (In Linux 2.5.32-2.5.48 there was a flag CLONE_SETTID that did this.) The store operation completes before the clone call returns control to user space.

CLONE_PID (Linux 2.0 to Linux 2.5.15)

If CLONE_PID is set, the child process is created with the same process ID as the calling process. This is good for hacking the system, but otherwise of not much use. From Linux 2.3.21 onward, this flag could be specified only by the system boot process (PID 0). The flag disappeared completely from the kernel sources in Linux 2.5.16. Subsequently, the kernel silently ignored this bit if it was specified in the flags mask. Much later, the same bit was recycled for use as the CLONE_PIDFD flag.

CLONE_PIDFD (since Linux 5.2)

If this flag is specified, a PID file descriptor referring to the child process is allocated and placed at a specified location in the parent's memory. The close-on-exec flag is set on this new file descriptor. PID file descriptors can be used for the purposes described in pidfd_open(2).

•

When using clone3(), the PID file descriptor is placed at the location pointed to by cl_args.pidfd.

•

When using clone(), the PID file descriptor is placed at the location pointed to by parent_tid. Since the parent_tid argument is used to return the PID file descriptor, CLONE_PIDFD cannot be used with CLONE_PARENT_SETTID when calling clone().

It is currently not possible to use this flag together with CLONE_THREAD. This means that the process identified by the PID file descriptor will always be a thread group leader.

If the obsolete CLONE_DETACHED flag is specified alongside CLONE_PIDFD when calling clone(), an error is returned. An error also results if CLONE_DETACHED is specified when calling clone3(). This error behavior ensures that the bit corresponding to CLONE_DETACHED can be reused for further PID file descriptor features in the future.

CLONE_PTRACE (since Linux 2.2)

If CLONE_PTRACE is specified, and the calling process is being traced, then trace the child also (see ptrace(2)).

CLONE_SETTLS (since Linux 2.5.32)

The TLS (Thread Local Storage) descriptor is set to tls.

The interpretation of tls and the resulting effect is architecture dependent. On x86, tls is interpreted as a struct user_desc * (see set_thread_area(2)). On x86-64 it is the new value to be set for the %fs base register (see the ARCH_SET_FS argument to arch_prctl(2)). On architectures with a dedicated TLS register, it is the new value of that register.

Use of this flag requires detailed knowledge and generally it should not be used except in libraries implementing threading.

CLONE_SIGHAND (since Linux 2.0)

If CLONE_SIGHAND is set, the calling process and the child process share the same table of signal handlers. If the calling process or child process calls sigaction(2) to change the behavior associated with a signal, the behavior is changed in the other process as well. However, the calling process and child processes still have distinct signal masks and sets of pending signals. So, one of them may block or unblock signals using sigprocmask(2) without affecting the other process.

If CLONE_SIGHAND is not set, the child process inherits a copy of the signal handlers of the calling process at the time of the clone call. Calls to sigaction(2) performed later by one of the processes have no effect on the other process.

Since Linux 2.6.0, the flags mask must also include CLONE_VM if CLONE_SIGHAND is specified.

CLONE_STOPPED (since Linux 2.6.0)

If CLONE_STOPPED is set, then the child is initially stopped (as though it was sent a SIGSTOP signal), and must be resumed by sending it a SIGCONT signal.

This flag was deprecated from Linux 2.6.25 onward, and was removed altogether in Linux 2.6.38. Since then, the kernel silently ignores it without error. Starting with Linux 4.6, the same bit was reused for the CLONE_NEWCGROUP flag.

CLONE_SYSVSEM (since Linux 2.5.10)

If CLONE_SYSVSEM is set, then the child and the calling process share a single list of System V semaphore adjustment (semadj) values (see semop(2)). In this case, the shared list accumulates semadj values across all processes sharing the list, and semaphore adjustments are performed only when the last process that is sharing the list terminates (or ceases sharing the list using unshare(2)). If this flag is not set, then the child has a separate semadj list that is initially empty.

CLONE_THREAD (since Linux 2.4.0)

If CLONE_THREAD is set, the child is placed in the same thread group as the calling process. To make the remainder of the discussion of CLONE_THREAD more readable, the term "thread" is used to refer to the processes within a thread group.

Thread groups were a feature added in Linux 2.4 to support the POSIX threads notion of a set of threads that share a single PID. Internally, this shared PID is the so-called thread group identifier (TGID) for the thread group. Since Linux 2.4, calls to getpid(2) return the TGID of the caller.

The threads within a group can be distinguished by their (system-wide) unique thread IDs (TID). A new thread's TID is available as the function result returned to the caller, and a thread can obtain its own TID using gettid(2).

When a clone call is made without specifying CLONE_THREAD, then the resulting thread is placed in a new thread group whose TGID is the same as the thread's TID. This thread is the leader of the new thread group.

A new thread created with CLONE_THREAD has the same parent process as the process that made the clone call (i.e., like CLONE_PARENT), so that calls to getppid(2) return the same value for all of the threads in a thread group. When a CLONE_THREAD thread terminates, the thread that created it is not sent a SIGCHLD (or other termination) signal; nor can the status of such a thread be obtained using wait(2). (The thread is said to be detached.)

After all of the threads in a thread group terminate the parent process of the thread group is sent a SIGCHLD (or other termination) signal.

If any of the threads in a thread group performs an execve(2), then all threads other than the thread group leader are terminated, and the new program is executed in the thread group leader.

If one of the threads in a thread group creates a child using fork(2), then any thread in the group can wait(2) for that child.

Since Linux 2.5.35, the flags mask must also include CLONE_SIGHAND if CLONE_THREAD is specified (and note that, since Linux 2.6.0, CLONE_SIGHAND also requires CLONE_VM to be included).

Signal dispositions and actions are process-wide: if an unhandled signal is delivered to a thread, then it will affect (terminate, stop, continue, be ignored in) all members of the thread group.

Each thread has its own signal mask, as set by sigprocmask(2).

A signal may be process-directed or thread-directed. A process-directed signal is targeted at a thread group (i.e., a TGID), and is delivered to an arbitrarily selected thread from among those that are not blocking the signal. A signal may be process-directed because it was generated by the kernel for reasons other than a hardware exception, or because it was sent using kill(2) or sigqueue(3). A thread-directed signal is targeted at (i.e., delivered to) a specific thread. A signal may be thread directed because it was sent using tgkill(2) or pthread_sigqueue(3), or because the thread executed a machine language instruction that triggered a hardware exception (e.g., invalid memory access triggering SIGSEGV or a floating-point exception triggering SIGFPE).

A call to sigpending(2) returns a signal set that is the union of the pending process-directed signals and the signals that are pending for the calling thread.

If a process-directed signal is delivered to a thread group, and the thread group has installed a handler for the signal, then the handler is invoked in exactly one, arbitrarily selected member of the thread group that has not blocked the signal. If multiple threads in a group are waiting to accept the same signal using sigwaitinfo(2), the kernel will arbitrarily select one of these threads to receive the signal.

CLONE_UNTRACED (since Linux 2.5.46)

If CLONE_UNTRACED is specified, then a tracing process cannot force CLONE_PTRACE on this child process.

CLONE_VFORK (since Linux 2.2)

If CLONE_VFORK is set, the execution of the calling process is suspended until the child releases its virtual memory resources via a call to execve(2) or _exit(2) (as with vfork(2)).

If CLONE_VFORK is not set, then both the calling process and the child are schedulable after the call, and an application should not rely on execution occurring in any particular order.

CLONE_VM (since Linux 2.0)

If CLONE_VM is set, the calling process and the child process run in the same memory space. In particular, memory writes performed by the calling process or by the child process are also visible in the other process. Moreover, any memory mapping or unmapping performed with mmap(2) or munmap(2) by the child or calling process also affects the other process.

If CLONE_VM is not set, the child process runs in a separate copy of the memory space of the calling process at the time of the clone call. Memory writes or file mappings/unmappings performed by one of the processes do not affect the other, as with fork(2).

If the CLONE_VM flag is specified and the CLONE_VFORK flag is not specified, then any alternate signal stack that was established by sigaltstack(2) is cleared in the child process.

## RETURN VALUE
On success, the thread ID of the child process is returned in the caller's thread of execution. On failure, -1 is returned in the caller's context, no child process is created, and errno is set to indicate the error.

## ERRORS
EACCES (clone3() only)

CLONE_INTO_CGROUP was specified in cl_args.flags, but the restrictions (described in cgroups(7)) on placing the child process into the version 2 cgroup referred to by cl_args.cgroup are not met.

EAGAIN

Too many processes are already running; see fork(2).

EBUSY (clone3() only)

CLONE_INTO_CGROUP was specified in cl_args.flags, but the file descriptor specified in cl_args.cgroup refers to a version 2 cgroup in which a domain controller is enabled.

EEXIST (clone3() only)

One (or more) of the PIDs specified in set_tid already exists in the corresponding PID namespace.

EINVAL

Both CLONE_SIGHAND and CLONE_CLEAR_SIGHAND were specified in the flags mask.

EINVAL

CLONE_SIGHAND was specified in the flags mask, but CLONE_VM was not. (Since Linux 2.6.0.)

EINVAL

CLONE_THREAD was specified in the flags mask, but CLONE_SIGHAND was not. (Since Linux 2.5.35.)

EINVAL

CLONE_THREAD was specified in the flags mask, but the current process previously called unshare(2) with the CLONE_NEWPID flag or used setns(2) to reassociate itself with a PID namespace.

EINVAL

Both CLONE_FS and CLONE_NEWNS were specified in the flags mask.

EINVAL (since Linux 3.9)

Both CLONE_NEWUSER and CLONE_FS were specified in the flags mask.

EINVAL

Both CLONE_NEWIPC and CLONE_SYSVSEM were specified in the flags mask.

EINVAL

One (or both) of CLONE_NEWPID or CLONE_NEWUSER and one (or both) of CLONE_THREAD or CLONE_PARENT were specified in the flags mask.

EINVAL (since Linux 2.6.32)

CLONE_PARENT was specified, and the caller is an init process.

EINVAL

Returned by the glibc clone() wrapper function when fn or stack is specified as NULL.

EINVAL

CLONE_NEWIPC was specified in the flags mask, but the kernel was not configured with the CONFIG_SYSVIPC and CONFIG_IPC_NS options.

EINVAL

CLONE_NEWNET was specified in the flags mask, but the kernel was not configured with the CONFIG_NET_NS option.

EINVAL

CLONE_NEWPID was specified in the flags mask, but the kernel was not configured with the CONFIG_PID_NS option.

EINVAL

CLONE_NEWUSER was specified in the flags mask, but the kernel was not configured with the CONFIG_USER_NS option.

EINVAL

CLONE_NEWUTS was specified in the flags mask, but the kernel was not configured with the CONFIG_UTS_NS option.

EINVAL

stack is not aligned to a suitable boundary for this architecture. For example, on aarch64, stack must be a multiple of 16.

EINVAL (clone3() only)

CLONE_DETACHED was specified in the flags mask.

EINVAL (clone() only)

CLONE_PIDFD was specified together with CLONE_DETACHED in the flags mask.

EINVAL

CLONE_PIDFD was specified together with CLONE_THREAD in the flags mask.

EINVAL (clone() only)

CLONE_PIDFD was specified together with CLONE_PARENT_SETTID in the flags mask.

EINVAL (clone3() only)

set_tid_size is greater than the number of nested PID namespaces.

EINVAL (clone3() only)

One of the PIDs specified in set_tid was an invalid.

EINVAL (clone3() only)

CLONE_THREAD or CLONE_PARENT was specified in the flags mask, but a signal was specified in exit_signal.

EINVAL (AArch64 only, Linux 4.6 and earlier)

stack was not aligned to a 128-bit boundary.

ENOMEM

Cannot allocate sufficient memory to allocate a task structure for the child, or to copy those parts of the caller's context that need to be copied.

ENOSPC (since Linux 3.7)

CLONE_NEWPID was specified in the flags mask, but the limit on the nesting depth of PID namespaces would have been exceeded; see pid_namespaces(7).

ENOSPC (since Linux 4.9; beforehand EUSERS)

CLONE_NEWUSER was specified in the flags mask, and the call would cause the limit on the number of nested user namespaces to be exceeded. See user_namespaces(7).

From Linux 3.11 to Linux 4.8, the error diagnosed in this case was EUSERS.

ENOSPC (since Linux 4.9)

One of the values in the flags mask specified the creation of a new user namespace, but doing so would have caused the limit defined by the corresponding file in /proc/sys/user to be exceeded. For further details, see namespaces(7).

EOPNOTSUPP (clone3() only)

CLONE_INTO_CGROUP was specified in cl_args.flags, but the file descriptor specified in cl_args.cgroup refers to a version 2 cgroup that is in the domain invalid state.

EPERM

CLONE_NEWCGROUP, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWNS, CLONE_NEWPID, or CLONE_NEWUTS was specified by an unprivileged process (process without CAP_SYS_ADMIN).

EPERM

CLONE_PID was specified by a process other than process 0. (This error occurs only on Linux 2.5.15 and earlier.)

EPERM

CLONE_NEWUSER was specified in the flags mask, but either the effective user ID or the effective group ID of the caller does not have a mapping in the parent namespace (see user_namespaces(7)).

EPERM (since Linux 3.9)

CLONE_NEWUSER was specified in the flags mask and the caller is in a chroot environment (i.e., the caller's root directory does not match the root directory of the mount namespace in which it resides).

EPERM (clone3() only)

set_tid_size was greater than zero, and the caller lacks the CAP_SYS_ADMIN capability in one or more of the user namespaces that own the corresponding PID namespaces.

ERESTARTNOINTR (since Linux 2.6.17)

System call was interrupted by a signal and will be restarted. (This can be seen only during a trace.)

EUSERS (Linux 3.11 to Linux 4.8)

CLONE_NEWUSER was specified in the flags mask, and the limit on the number of nested user namespaces would be exceeded. See the discussion of the ENOSPC error above.

## VERSIONS
The glibc clone() wrapper function makes some changes in the memory pointed to by stack (changes required to set the stack up correctly for the child) before invoking the clone() system call. So, in cases where clone() is used to recursively create children, do not use the buffer employed for the parent's stack as the stack of the child.

On i386, clone() should not be called through vsyscall, but directly through int $0x80.

### C library/kernel differences
The raw clone() system call corresponds more closely to fork(2) in that execution in the child continues from the point of the call. As such, the fn and arg arguments of the clone() wrapper function are omitted.

In contrast to the glibc wrapper, the raw clone() system call accepts NULL as a stack argument (and clone3() likewise allows cl_args.stack to be NULL). In this case, the child uses a duplicate of the parent's stack. (Copy-on-write semantics ensure that the child gets separate copies of stack pages when either process modifies the stack.) In this case, for correct operation, the CLONE_VM option should not be specified. (If the child shares the parent's memory because of the use of the CLONE_VM flag, then no copy-on-write duplication occurs and chaos is likely to result.)

The order of the arguments also differs in the raw system call, and there are variations in the arguments across architectures, as detailed in the following paragraphs.

The raw system call interface on x86-64 and some other architectures (including sh, tile, and alpha) is:

```
long clone(unsigned long flags, void *stack,
           int *parent_tid, int *child_tid,
           unsigned long tls);
```

On x86-32, and several other common architectures (including score, ARM, ARM 64, PA-RISC, arc, Power PC, xtensa, and MIPS), the order of the last two arguments is reversed:

```
long clone(unsigned long flags, void *stack,
          int *parent_tid, unsigned long tls,
          int *child_tid);
```

On the cris and s390 architectures, the order of the first two arguments is reversed:

```
long clone(void *stack, unsigned long flags,
           int *parent_tid, int *child_tid,
           unsigned long tls);
```

On the microblaze architecture, an additional argument is supplied:

```
long clone(unsigned long flags, void *stack,
           int stack_size,         /* Size of stack */
           int *parent_tid, int *child_tid,
           unsigned long tls);
```

### blackfin, m68k, and sparc
The argument-passing conventions on blackfin, m68k, and sparc are different from the descriptions above. For details, see the kernel (and glibc) source.

### ia64
On ia64, a different interface is used:

```
int __clone2(int (*fn)(void *),
             void *stack_base, size_t stack_size,
             int flags, void *arg, ...
          /* pid_t *parent_tid, struct user_desc *tls,
             pid_t *child_tid */ );
```

The prototype shown above is for the glibc wrapper function; for the system call itself, the prototype can be described as follows (it is identical to the clone() prototype on microblaze):

```
long clone2(unsigned long flags, void *stack_base,
            int stack_size,         /* Size of stack */
            int *parent_tid, int *child_tid,
            unsigned long tls);
```

__clone2() operates in the same way as clone(), except that stack_base points to the lowest address of the child's stack area, and stack_size specifies the size of the stack pointed to by stack_base.

## STANDARDS
Linux.

## HISTORY
clone3()

Linux 5.3.

### Linux 2.4 and earlier
In the Linux 2.4.x series, CLONE_THREAD generally does not make the parent of the new thread the same as the parent of the calling process. However, from Linux 2.4.7 to Linux 2.4.18 the CLONE_THREAD flag implied the CLONE_PARENT flag (as in Linux 2.6.0 and later).

In Linux 2.4 and earlier, clone() does not take arguments parent_tid, tls, and child_tid.

## NOTES
One use of these systems calls is to implement threads: multiple flows of control in a program that run concurrently in a shared address space.

The kcmp(2) system call can be used to test whether two processes share various resources such as a file descriptor table, System V semaphore undo operations, or a virtual address space.

Handlers registered using pthread_atfork(3) are not executed during a clone call.

## BUGS
GNU C library versions 2.3.4 up to and including 2.24 contained a wrapper function for getpid(2) that performed caching of PIDs. This caching relied on support in the glibc wrapper for clone(), but limitations in the implementation meant that the cache was not up to date in some circumstances. In particular, if a signal was delivered to the child immediately after the clone() call, then a call to getpid(2) in a handler for the signal could return the PID of the calling process ("the parent"), if the clone wrapper had not yet had a chance to update the PID cache in the child. (This discussion ignores the case where the child was created using CLONE_THREAD, when getpid(2) should return the same value in the child and in the process that called clone(), since the caller and the child are in the same thread group. The stale-cache problem also does not occur if the flags argument includes CLONE_VM.) To get the truth, it was sometimes necessary to use code such as the following:

```
#include <syscall.h>
pid_t mypid;
mypid = syscall(SYS_getpid);
```

Because of the stale-cache problem, as well as other problems noted in getpid(2), the PID caching feature was removed in glibc 2.25.

## EXAMPLES
The following program demonstrates the use of clone() to create a child process that executes in a separate UTS namespace. The child changes the hostname in its UTS namespace. Both parent and child then display the system hostname, making it possible to see that the hostname differs in the UTS namespaces of the parent and child. For an example of the use of this program, see setns(2).

Within the sample program, we allocate the memory that is to be used for the child's stack using mmap(2) rather than malloc(3) for the following reasons:

•

mmap(2) allocates a block of memory that starts on a page boundary and is a multiple of the page size. This is useful if we want to establish a guard page (a page with protection PROT_NONE) at the end of the stack using mprotect(2).

•

We can specify the MAP_STACK flag to request a mapping that is suitable for a stack. For the moment, this flag is a no-op on Linux, but it exists and has effect on some other systems, so we should include it for portability.

### Program source

```
#define _GNU_SOURCE
#include <err.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <unistd.h>
static int              /* Start function for cloned child */
childFunc(void *arg)
{

    struct utsname uts;

    /* Change hostname in UTS namespace of child. */

    if (sethostname(arg, strlen(arg)) == -1)

        err(EXIT_FAILURE, "sethostname");

    /* Retrieve and display hostname. */

    if (uname(&uts) == -1)

        err(EXIT_FAILURE, "uname");

    printf("uts.nodename in child:  %s\n", uts.nodename);

    /* Keep the namespace open for a while, by sleeping.

       This allows some experimentation--for example, another

       process might join the namespace. */

    sleep(200);

    return 0;           /* Child terminates now */
}
#define STACK_SIZE (1024 * 1024)    /* Stack size for cloned child */
int
main(int argc, char *argv[])
{

    char            *stack;         /* Start of stack buffer */

    char            *stackTop;      /* End of stack buffer */

    pid_t           pid;

    struct utsname  uts;

    if (argc < 2) {

        fprintf(stderr, "Usage: %s <child-hostname>\n", argv[0]);

        exit(EXIT_SUCCESS);

    }

    /* Allocate memory to be used for the stack of the child. */

    stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,

                 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);

    if (stack == MAP_FAILED)

        err(EXIT_FAILURE, "mmap");

    stackTop = stack + STACK_SIZE;  /* Assume stack grows downward */

    /* Create child that has its own UTS namespace;

       child commences execution in childFunc(). */

    pid = clone(childFunc, stackTop, CLONE_NEWUTS | SIGCHLD, argv[1]);

    if (pid == -1)

        err(EXIT_FAILURE, "clone");

    printf("clone() returned %jd\n", (intmax_t) pid);

    /* Parent falls through to here */

    sleep(1);           /* Give child time to change its hostname */

    /* Display hostname in parent's UTS namespace. This will be

       different from hostname in child's UTS namespace. */

    if (uname(&uts) == -1)

        err(EXIT_FAILURE, "uname");

    printf("uts.nodename in parent: %s\n", uts.nodename);

    if (waitpid(pid, NULL, 0) == -1)    /* Wait for child */

        err(EXIT_FAILURE, "waitpid");

    printf("child has terminated\n");

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
fork(2), futex(2), getpid(2), gettid(2), kcmp(2), mmap(2), pidfd_open(2), set_thread_area(2), set_tid_address(2), setns(2), tkill(2), unshare(2), wait(2), capabilities(7), namespaces(7), pthreads(7)


close

package: man-pages

title: close(2)

summary: close a file descriptor

text:
# close(2)

## NAME
close - close a file descriptor

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

## SYNOPSIS

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

```
int close(int fd);
```

## DESCRIPTION
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed; if the file descriptor was the last reference to a file which has been removed using unlink(2), the file is deleted.

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

## ERRORS
EBADF

fd isn't a valid open file descriptor.

EINTR

The close() call was interrupted by a signal; see signal(7).

EIO

An I/O error occurred.

ENOSPC, EDQUOT

On NFS, these errors are not normally reported against the first write which exceeds the available storage space, but instead against a subsequent write(2), fsync(2), or close().

See NOTES for a discussion of why close() should not be retried after an error.

## STANDARDS
POSIX.1-2008.

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

## NOTES
A successful close does not guarantee that the data has been successfully saved to disk, as the kernel uses the buffer cache to defer writes. Typically, filesystems do not flush buffers when a file is closed. If you need to be sure that the data is physically stored on the underlying disk, use fsync(2). (It will depend on the disk hardware at this point.)

The close-on-exec file descriptor flag can be used to ensure that a file descriptor is automatically closed upon a successful execve(2); see fcntl(2) for details.

### Multithreaded processes and close()
It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be reused, there are some obscure race conditions that may cause unintended side effects.

Furthermore, consider the following scenario where two threads are performing operations on the same file descriptor:

(1)

One thread is blocked in an I/O system call on the file descriptor. For example, it is trying to write(2) to a pipe that is already full, or trying to read(2) from a stream socket which currently has no available data.

(2)

Another thread closes the file descriptor.

The behavior in this situation varies across systems. On some systems, when the file descriptor is closed, the blocking system call returns immediately with an error.

On Linux (and possibly some other systems), the behavior is different: the blocking I/O system call holds a reference to the underlying open file description, and this reference keeps the description open until the I/O system call completes. (See open(2) for a discussion of open file descriptions.) Thus, the blocking system call in the first thread may successfully complete after the close() in the second thread.

### Dealing with error returns from close()
A careful programmer will check the return value of close(), since it is quite possible that errors on a previous write(2) operation are reported only on the final close() that releases the open file description. Failing to check the return value when closing a file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

Note, however, that a failure return should be used only for diagnostic purposes (i.e., a warning to the application that there may still be I/O pending or there may have been failed I/O) or remedial purposes (e.g., writing the file once more or creating a backup).

Retrying the close() after a failure return is the wrong thing to do, since this may cause a reused file descriptor from another thread to be closed. This can occur because the Linux kernel always releases the file descriptor early in the close operation, freeing it for reuse; the steps that may return an error, such as flushing data to the filesystem or device, occur only later in the close operation.

Many other implementations similarly always close the file descriptor (except in the case of EBADF, meaning that the file descriptor was invalid) even if they subsequently report an error on return from close(). POSIX.1 is currently silent on this point, but there are plans to mandate this behavior in the next major release of the standard.

A careful programmer who wants to know about I/O errors may precede close() with a call to fsync(2).

The EINTR error is a somewhat special case. Regarding the EINTR error, POSIX.1-2008 says:

If close() is interrupted by a signal that is to be caught, it shall return -1 with errno set to EINTR and the state of fildes is unspecified.

This permits the behavior that occurs on Linux and many other implementations, where, as with other errors that may be reported by close(), the file descriptor is guaranteed to be closed. However, it also permits another possibility: that the implementation returns an EINTR error and keeps the file descriptor open. (According to its documentation, HP-UX's close() does this.) The caller must then once more use close() to close the file descriptor, to avoid file descriptor leaks. This divergence in implementation behaviors provides a difficult hurdle for portable applications, since on many implementations, close() must not be called again after an EINTR error, and on at least one, close() must be called again. There are plans to address this conundrum for the next major release of the POSIX.1 standard.

## SEE ALSO
close_range(2), fcntl(2), fsync(2), open(2), shutdown(2), unlink(2), fclose(3)

branch: sisyphus


title: close_range(2)

text:
# close_range(2)

## NAME
close_range - close all file descriptors in a given range

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

## SYNOPSIS

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

```
int close_range(unsigned int first, unsigned int last,
                unsigned int flags);
```

## DESCRIPTION
The close_range() system call closes all open file descriptors from first to last (included).

Errors closing a given file descriptor are currently ignored.

flags is a bit mask containing 0 or more of the following:

CLOSE_RANGE_CLOEXEC (since Linux 5.11)

Set the close-on-exec flag on the specified file descriptors, rather than immediately closing them.

CLOSE_RANGE_UNSHARE

Unshare the specified file descriptors from any other processes before closing them, avoiding races with other threads sharing the file descriptor table.

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

## ERRORS
EINVAL

flags is not valid, or first is greater than last.

The following can occur with CLOSE_RANGE_UNSHARE (when constructing the new descriptor table):

EMFILE

The number of open file descriptors exceeds the limit specified in /proc/sys/fs/nr_open (see proc(5)). This error can occur in situations where that limit was lowered before a call to close_range() where the CLOSE_RANGE_UNSHARE flag is specified.

ENOMEM

Insufficient kernel memory was available.

## STANDARDS
None.

## HISTORY
FreeBSD. Linux 5.9, glibc 2.34.

## NOTES

### Closing all open file descriptors
To avoid blindly closing file descriptors in the range of possible file descriptors, this is sometimes implemented (on Linux) by listing open file descriptors in /proc/self/fd/ and calling close(2) on each one. close_range() can take care of this without requiring /proc and within a single system call, which provides significant performance benefits.

### Closing file descriptors before exec
File descriptors can be closed safely using

```
/* we don't want anything past stderr here */
close_range(3, ~0U, CLOSE_RANGE_UNSHARE);
execve(....);
```

CLOSE_RANGE_UNSHARE is conceptually equivalent to

```
unshare(CLONE_FILES);
close_range(first, last, 0);
```

but can be more efficient: if the unshared range extends past the current maximum number of file descriptors allocated in the caller's file descriptor table (the common case when last is ~0U), the kernel will unshare a new file descriptor table for the caller up to first, copying as few file descriptors as possible. This avoids subsequent close(2) calls entirely; the whole operation is complete once the table is unshared.

### Closing files on exec
This is particularly useful in cases where multiple pre-exec setup steps risk conflicting with each other. For example, setting up a seccomp(2) profile can conflict with a close_range() call: if the file descriptors are closed before the seccomp(2) profile is set up, the profile setup can't use them itself, or control their closure; if the file descriptors are closed afterwards, the seccomp profile can't block the close_range() call or any fallbacks. Using CLOSE_RANGE_CLOEXEC avoids this: the descriptors can be marked before the seccomp(2) profile is set up, and the profile can control access to close_range() without affecting the calling process.

## EXAMPLES
The program shown below opens the files named in its command-line arguments, displays the list of files that it has opened (by iterating through the entries in /proc/PID/fd), uses close_range() to close all file descriptors greater than or equal to 3, and then once more displays the process's list of open files. The following example demonstrates the use of the program:

```
$ touch /tmp/a /tmp/b /tmp/c
$ ./a.out /tmp/a /tmp/b /tmp/c
/tmp/a opened as FD 3
/tmp/b opened as FD 4
/tmp/c opened as FD 5
/proc/self/fd/0 ==> /dev/pts/1
/proc/self/fd/1 ==> /dev/pts/1
/proc/self/fd/2 ==> /dev/pts/1
/proc/self/fd/3 ==> /tmp/a
/proc/self/fd/4 ==> /tmp/b
/proc/self/fd/5 ==> /tmp/b
/proc/self/fd/6 ==> /proc/9005/fd
========= About to call close_range() =======
/proc/self/fd/0 ==> /dev/pts/1
/proc/self/fd/1 ==> /dev/pts/1
/proc/self/fd/2 ==> /dev/pts/1
/proc/self/fd/3 ==> /proc/9005/fd
```

Note that the lines showing the pathname /proc/9005/fd result from the calls to opendir(3).

### Program source

```
#define _GNU_SOURCE
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
/* Show the contents of the symbolic links in /proc/self/fd */
static void
show_fds(void)
{

    DIR            *dirp;

    char           path[PATH_MAX], target[PATH_MAX];

    ssize_t        len;

    struct dirent  *dp;

    dirp = opendir("/proc/self/fd");

    if (dirp  == NULL) {

        perror("opendir");

        exit(EXIT_FAILURE);

    }

    for (;;) {

        dp = readdir(dirp);

        if (dp == NULL)

            break;

        if (dp->d_type == DT_LNK) {

            snprintf(path, sizeof(path), "/proc/self/fd/%s",

                     dp->d_name);

            len = readlink(path, target, sizeof(target));

            printf("%s ==> %.*s\n", path, (int) len, target);

        }

    }

    closedir(dirp);
}
int
main(int argc, char *argv[])
{

    int  fd;

    for (size_t j = 1; j < argc; j++) {

        fd = open(argv[j], O_RDONLY);

        if (fd == -1) {

            perror(argv[j]);

            exit(EXIT_FAILURE);

        }

        printf("%s opened as FD %d\n", argv[j], fd);

    }

    show_fds();

    printf("========= About to call close_range() =======\n");

    if (syscall(SYS_close_range, 3, ~0U, 0) == -1) {

        perror("close_range");

        exit(EXIT_FAILURE);

    }

    show_fds();

    exit(EXIT_FAILURE);
}
```

## SEE ALSO
close(2)


connect

title: connect(2)

summary: initiate a connection on a socket

text:
# connect(2)

## NAME
connect - initiate a connection on a socket

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

## SYNOPSIS

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

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

## DESCRIPTION
The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr. The format of the address in addr is determined by the address space of the socket sockfd; see socket(2) for further details.

If the socket sockfd is of type SOCK_DGRAM, then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received. If the socket is of type SOCK_STREAM or SOCK_SEQPACKET, this call attempts to make a connection to the socket that is bound to the address specified by addr.

Some protocol sockets (e.g., UNIX domain stream sockets) may successfully connect() only once.

Some protocol sockets (e.g., datagram sockets in the UNIX and Internet domains) may use connect() multiple times to change their association.

Some protocol sockets (e.g., TCP sockets as well as datagram sockets in the UNIX and Internet domains) may dissolve the association by connecting to an address with the sa_family member of sockaddr set to AF_UNSPEC; thereafter, the socket can be connected to another address. (AF_UNSPEC is supported since Linux 2.2.)

## RETURN VALUE
If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
The following are general socket errors only. There may be other domain-specific error codes.

EACCES

For UNIX domain sockets, which are identified by pathname: Write permission is denied on the socket file, or search permission is denied for one of the directories in the path prefix. (See also path_resolution(7).)

EACCES, EPERM

The user tried to connect to a broadcast address without having the socket broadcast flag enabled or the connection request failed because of a local firewall rule.

EACCES

It can also be returned if an SELinux policy denied a connection (for example, if there is a policy saying that an HTTP proxy can only connect to ports associated with HTTP servers, and the proxy tries to connect to a different port).

EADDRINUSE

Local address is already in use.

EADDRNOTAVAIL

(Internet domain sockets) The socket referred to by sockfd had not previously been bound to an address and, upon attempting to bind it 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 in ip(7).

EAFNOSUPPORT

The passed address didn't have the correct address family in its sa_family field.

EAGAIN

For nonblocking UNIX domain sockets, the socket is nonblocking, and the connection cannot be completed immediately. For other socket families, there are insufficient entries in the routing cache.

EALREADY

The socket is nonblocking and a previous connection attempt has not yet been completed.

EBADF

sockfd is not a valid open file descriptor.

ECONNREFUSED

A connect() on a stream socket found no one listening on the remote address.

EFAULT

The socket structure address is outside the user's address space.

EINPROGRESS

The socket is nonblocking and the connection cannot be completed immediately. (UNIX domain sockets failed with EAGAIN instead.) It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).

EINTR

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

EISCONN

The socket is already connected.

ENETUNREACH

Network is unreachable.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

EPROTOTYPE

The socket type does not support the requested communications protocol. This error can occur, for example, on an attempt to connect a UNIX domain datagram socket to a stream socket.

ETIMEDOUT

Timeout while attempting connection. The server may be too busy to accept new connections. Note that for IP sockets the timeout may be very long when syncookies are enabled on the server.

## STANDARDS
POSIX.1-2008.

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

## NOTES
If connect() fails, consider the state of the socket as unspecified. Portable applications should close the socket and create a new one for reconnecting.

## EXAMPLES
An example of the use of connect() is shown in getaddrinfo(3).

## SEE ALSO
accept(2), bind(2), getsockname(2), listen(2), socket(2), path_resolution(7), selinux(8)


title: copy_file_range(2)

text:
# copy_file_range(2)

## NAME
copy_file_range - Copy a range of data from one file to another

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

## SYNOPSIS

```
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
```

```
ssize_t copy_file_range(int fd_in, off_t *_Nullable off_in,
                        int fd_out, off_t *_Nullable off_out,
                        size_t len, unsigned int flags);
```

## DESCRIPTION
The copy_file_range() system call performs an in-kernel copy between two file descriptors without the additional cost of transferring data from the kernel to user space and then back into the kernel. It copies up to len bytes of data from the source file descriptor fd_in to the target file descriptor fd_out, overwriting any data that exists within the requested range of the target file.

The following semantics apply for off_in, and similar statements apply to off_out:

•

If off_in is NULL, then bytes are read from fd_in starting from the file offset, and the file offset is adjusted by the number of bytes copied.

•

If off_in is not NULL, then off_in must point to a buffer that specifies the starting offset where bytes from fd_in will be read. The file offset of fd_in is not changed, but off_in is adjusted appropriately.

fd_in and fd_out can refer to the same file. If they refer to the same file, then the source and target ranges are not allowed to overlap.

The flags argument is provided to allow for future extensions and currently must be set to 0.

## RETURN VALUE
Upon successful completion, copy_file_range() will return the number of bytes copied between files. This could be less than the length originally requested. If the file offset of fd_in is at or past the end of file, no bytes are copied, and copy_file_range() returns zero.

On error, copy_file_range() returns -1 and errno is set to indicate the error.

## ERRORS
EBADF

One or more file descriptors are not valid.

EBADF

fd_in is not open for reading; or fd_out is not open for writing.

EBADF

The O_APPEND flag is set for the open file description (see open(2)) referred to by the file descriptor fd_out.

EFBIG

An attempt was made to write at a position past the maximum file offset the kernel supports.

EFBIG

An attempt was made to write a range that exceeds the allowed maximum file size. The maximum file size differs between filesystem implementations and can be different from the maximum allowed file offset.

EFBIG

An attempt was made to write beyond the process's file size resource limit. This may also result in the process receiving a SIGXFSZ signal.

EINVAL

The flags argument is not 0.

EINVAL

fd_in and fd_out refer to the same file and the source and target ranges overlap.

EINVAL

Either fd_in or fd_out is not a regular file.

EIO

A low-level I/O error occurred while copying.

EISDIR

Either fd_in or fd_out refers to a directory.

ENOMEM

Out of memory.

ENOSPC

There is not enough space on the target filesystem to complete the copy.

EOPNOTSUPP (since Linux 5.19)

The filesystem does not support this operation.

EOVERFLOW

The requested source or destination range is too large to represent in the specified data types.

EPERM

fd_out refers to an immutable file.

ETXTBSY

Either fd_in or fd_out refers to an active swap file.

EXDEV (before Linux 5.3)

The files referred to by fd_in and fd_out are not on the same filesystem.

EXDEV (since Linux 5.19)

The files referred to by fd_in and fd_out are not on the same filesystem, and the source and target filesystems are not of the same type, or do not support cross-filesystem copy.

## VERSIONS
A major rework of the kernel implementation occurred in Linux 5.3. Areas of the API that weren't clearly defined were clarified and the API bounds are much more strictly checked than on earlier kernels.

Since Linux 5.19, cross-filesystem copies can be achieved when both filesystems are of the same type, and that filesystem implements support for it. See BUGS for behavior prior to Linux 5.19.

Applications should target the behaviour and requirements of Linux 5.19, that was also backported to earlier stable kernels.

## STANDARDS
Linux, GNU.

## HISTORY
Linux 4.5, but glibc 2.27 provides a user-space emulation when it is not available.

## NOTES
If fd_in is a sparse file, then copy_file_range() may expand any holes existing in the requested range. Users may benefit from calling copy_file_range() in a loop, and using the lseek(2) SEEK_DATA and SEEK_HOLE operations to find the locations of data segments.

copy_file_range() gives filesystems an opportunity to implement "copy acceleration" techniques, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks) or server-side-copy (in the case of NFS).

_FILE_OFFSET_BITS should be defined to be 64 in code that uses non-null off_in or off_out or that takes the address of copy_file_range, if the code is intended to be portable to traditional 32-bit x86 and ARM platforms where off_t's width defaults to 32 bits.

## BUGS
In Linux 5.3 to Linux 5.18, cross-filesystem copies were implemented by the kernel, if the operation was not supported by individual filesystems. However, on some virtual filesystems, the call failed to copy, while still reporting success.

## EXAMPLES

```
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    int          fd_in, fd_out;

    off_t        len, ret;

    struct stat  stat;

    if (argc != 3) {

        fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd_in = open(argv[1], O_RDONLY);

    if (fd_in == -1) {

        perror("open (argv[1])");

        exit(EXIT_FAILURE);

    }

    if (fstat(fd_in, &stat) == -1) {

        perror("fstat");

        exit(EXIT_FAILURE);

    }

    len = stat.st_size;

    fd_out = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644);

    if (fd_out == -1) {

        perror("open (argv[2])");

        exit(EXIT_FAILURE);

    }

    do {

        ret = copy_file_range(fd_in, NULL, fd_out, NULL, len, 0);

        if (ret == -1) {

            perror("copy_file_range");

            exit(EXIT_FAILURE);

        }

        len -= ret;

    } while (len > 0 && ret > 0);

    close(fd_in);

    close(fd_out);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
lseek(2), sendfile(2), splice(2)


title: create_module(2)

summary: create a loadable module entry

text:
# create_module(2)

## NAME
create_module - create a loadable module entry

## SYNOPSIS

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

```
[[deprecated]] caddr_t create_module(const char *name, size_t size);
```

## DESCRIPTION
Note: This system call is present only before Linux 2.6.

create_module() attempts to create a loadable module entry and reserve the kernel memory that will be needed to hold the module. This system call requires privilege.

## RETURN VALUE
On success, returns the kernel address at which the module will reside. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EEXIST

A module by that name already exists.

EFAULT

name is outside the program's accessible address space.

EINVAL

The requested size is too small even for the module header information.

ENOMEM

The kernel could not allocate a contiguous block of memory large enough for the module.

ENOSYS

create_module() is not supported in this version of the kernel (e.g., Linux 2.6 or later).

EPERM

The caller was not privileged (did not have the CAP_SYS_MODULE capability).

## STANDARDS
Linux.

## HISTORY
Removed in Linux 2.6.

This obsolete system call is not supported by glibc. No declaration is provided in glibc headers, but, through a quirk of history, glibc versions before glibc 2.23 did export an ABI for this system call. Therefore, in order to employ this system call, it was sufficient to manually declare the interface in your code; alternatively, you could invoke the system call using syscall(2).

## SEE ALSO
delete_module(2), init_module(2), query_module(2)


title: delete_module(2)

summary: unload a kernel module

text:
# delete_module(2)

## NAME
delete_module - unload a kernel module

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

## SYNOPSIS

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

```
int syscall(SYS_delete_module, const char *name, unsigned int flags);
```

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

## DESCRIPTION
The delete_module() system call attempts to remove the unused loadable module entry identified by name. If the module has an exit function, then that function is executed before unloading the module. The flags argument is used to modify the behavior of the system call, as described below. This system call requires privilege.

Module removal is attempted according to the following rules:

(1)

If there are other loaded modules that depend on (i.e., refer to symbols defined in) this module, then the call fails.

(2)

Otherwise, if the reference count for the module (i.e., the number of processes currently using the module) is zero, then the module is immediately unloaded.

(3)

If a module has a nonzero reference count, then the behavior depends on the bits set in flags. In normal usage (see NOTES), the O_NONBLOCK flag is always specified, and the O_TRUNC flag may additionally be specified.

The various combinations for flags have the following effect:

flags == O_NONBLOCK

The call returns immediately, with an error.

flags == (O_NONBLOCK | O_TRUNC)

The module is unloaded immediately, regardless of whether it has a nonzero reference count.

(flags & O_NONBLOCK) == 0

If flags does not specify O_NONBLOCK, the following steps occur:

•

The module is marked so that no new references are permitted.

•

If the module's reference count is nonzero, the caller is placed in an uninterruptible sleep state (TASK_UNINTERRUPTIBLE) until the reference count is zero, at which point the call unblocks.

•

The module is unloaded in the usual way.

The O_TRUNC flag has one further effect on the rules described above. By default, if a module has an init function but no exit function, then an attempt to remove the module fails. However, if O_TRUNC was specified, this requirement is bypassed.

Using the O_TRUNC flag is dangerous! If the kernel was not built with CONFIG_MODULE_FORCE_UNLOAD, this flag is silently ignored. (Normally, CONFIG_MODULE_FORCE_UNLOAD is enabled.) Using this flag taints the kernel (TAINT_FORCED_RMMOD).

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

## ERRORS
EBUSY

The module is not "live" (i.e., it is still being initialized or is already marked for removal); or, the module has an init function but has no exit function, and O_TRUNC was not specified in flags.

EFAULT

name refers to a location outside the process's accessible address space.

ENOENT

No module by that name exists.

EPERM

The caller was not privileged (did not have the CAP_SYS_MODULE capability), or module unloading is disabled (see /proc/sys/kernel/modules_disabled in proc(5)).

EWOULDBLOCK

Other modules depend on this module; or, O_NONBLOCK was specified in flags, but the reference count of this module is nonzero and O_TRUNC was not specified in flags.

## STANDARDS
Linux.

## HISTORY
The delete_module() system call is not supported by glibc. No declaration is provided in glibc headers, but, through a quirk of history, glibc versions before glibc 2.23 did export an ABI for this system call. Therefore, in order to employ this system call, it is (before glibc 2.23) sufficient to manually declare the interface in your code; alternatively, you can invoke the system call using syscall(2).

### Linux 2.4 and earlier
In Linux 2.4 and earlier, the system call took only one argument:

int delete_module(const char *name);

If name is NULL, all unused modules marked auto-clean are removed.

Some further details of differences in the behavior of delete_module() in Linux 2.4 and earlier are not currently explained in this manual page.

## NOTES
The uninterruptible sleep that may occur if O_NONBLOCK is omitted from flags is considered undesirable, because the sleeping process is left in an unkillable state. As at Linux 3.7, specifying O_NONBLOCK is optional, but in future kernels it is likely to become mandatory.

## SEE ALSO
create_module(2), init_module(2), query_module(2), lsmod(8), modprobe(8), rmmod(8)


dup

title: dup(2)

summary: duplicate a file descriptor

text:
# dup(2)

## NAME
dup, dup2, dup3 - duplicate a file descriptor

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

## SYNOPSIS

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

```
int dup(int oldfd);
int dup2(int oldfd, int newfd);
```

```
#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <fcntl.h>              /* Definition of O_* constants */
#include <unistd.h>
```

```
int dup3(int oldfd, int newfd, int flags);
```

## DESCRIPTION
The dup() system call allocates a new file descriptor that refers to the same open file description as the descriptor oldfd. (For an explanation of open file descriptions, see open(2).) The new file descriptor number is guaranteed to be the lowest-numbered file descriptor that was unused in the calling process.

After a successful return, the old and new file descriptors may be used interchangeably. Since the two file descriptors refer to the same open file description, they share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the file descriptors, the offset is also changed for the other file descriptor.

The two file descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.

### dup2()
The dup2() system call performs the same task as dup(), but instead of using the lowest-numbered unused file descriptor, it uses the file descriptor number specified in newfd. In other words, the file descriptor newfd is adjusted so that it now refers to the same open file description as oldfd.

If the file descriptor newfd was previously open, it is closed before being reused; the close is performed silently (i.e., any errors during the close are not reported by dup2()).

The steps of closing and reusing the file descriptor newfd are performed atomically. This is important, because trying to implement equivalent functionality using close(2) and dup() would be subject to race conditions, whereby newfd might be reused between the two steps. Such reuse could happen because the main program is interrupted by a signal handler that allocates a file descriptor, or because a parallel thread allocates a file descriptor.

Note the following points:

•

If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.

•

If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd.

### dup3()
dup3() is the same as dup2(), except that:

•

The caller can force the close-on-exec flag to be set for the new file descriptor by specifying O_CLOEXEC in flags. See the description of the same flag in open(2) for reasons why this may be useful.

•

If oldfd equals newfd, then dup3() fails with the error EINVAL.

## RETURN VALUE
On success, these system calls return the new file descriptor. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EBADF

oldfd isn't an open file descriptor.

EBADF

newfd is out of the allowed range for file descriptors (see the discussion of RLIMIT_NOFILE in getrlimit(2)).

EBUSY

(Linux only) This may be returned by dup2() or dup3() during a race condition with open(2) and dup().

EINTR

The dup2() or dup3() call was interrupted by a signal; see signal(7).

EINVAL

(dup3()) flags contain an invalid value.

EINVAL

(dup3()) oldfd was equal to newfd.

EMFILE

The per-process limit on the number of open file descriptors has been reached (see the discussion of RLIMIT_NOFILE in getrlimit(2)).

## STANDARDS
dup()

dup2()

POSIX.1-2008.

dup3()

Linux.

## HISTORY
dup()

dup2()

POSIX.1-2001, SVr4, 4.3BSD.

dup3()

Linux 2.6.27, glibc 2.9.

## NOTES
The error returned by dup2() is different from that returned by fcntl(..., F_DUPFD, ...) when newfd is out of range. On some systems, dup2() also sometimes returns EINVAL like F_DUPFD.

If newfd was open, any errors that would have been reported at close(2) time are lost. If this is of concern, then—unless the program is single-threaded and does not allocate file descriptors in signal handlers—the correct approach is not to close newfd before calling dup2(), because of the race condition described above. Instead, code something like the following could be used:

```
/* Obtain a duplicate of 'newfd' that can subsequently

   be used to check for close() errors; an EBADF error

   means that 'newfd' was not open. */
tmpfd = dup(newfd);
if (tmpfd == -1 && errno != EBADF) {

    /* Handle unexpected dup() error. */
}
/* Atomically duplicate 'oldfd' on 'newfd'. */
if (dup2(oldfd, newfd) == -1) {

    /* Handle dup2() error. */
}
/* Now check for close() errors on the file originally

   referred to by 'newfd'. */
if (tmpfd != -1) {

    if (close(tmpfd) == -1) {

        /* Handle errors from close. */

    }
}
```

## SEE ALSO
close(2), fcntl(2), open(2), pidfd_getfd(2)


title: epoll_create(2)

summary: open an epoll file descriptor

text:
# epoll_create(2)

## NAME
epoll_create, epoll_create1 - open an epoll file descriptor

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

## SYNOPSIS

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

```
int epoll_create(int size);
int epoll_create1(int flags);
```

## DESCRIPTION
epoll_create() creates a new epoll(7) instance. Since Linux 2.6.8, the size argument is ignored, but must be greater than zero; see HISTORY.

epoll_create() returns a file descriptor referring to the new epoll instance. This file descriptor is used for all the subsequent calls to the epoll interface. When no longer required, the file descriptor returned by epoll_create() should be closed by using close(2). When all file descriptors referring to an epoll instance have been closed, the kernel destroys the instance and releases the associated resources for reuse.

### epoll_create1()
If flags is 0, then, other than the fact that the obsolete size argument is dropped, epoll_create1() is the same as epoll_create(). The following value can be included in flags to obtain different behavior:

EPOLL_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 (a nonnegative integer). On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

size is not positive.

EINVAL

(epoll_create1()) Invalid value specified 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.

ENOMEM

There was insufficient memory to create the kernel object.

## STANDARDS
Linux.

## HISTORY
epoll_create()

Linux 2.6, glibc 2.3.2.

epoll_create1()

Linux 2.6.27, glibc 2.9.

In the initial epoll_create() implementation, the size argument informed the kernel of the number of file descriptors that the caller expected to add to the epoll instance. The kernel used this information as a hint for the amount of space to initially allocate in internal data structures describing events. (If necessary, the kernel would allocate more space if the caller's usage exceeded the hint given in size.) Nowadays, this hint is no longer required (the kernel dynamically sizes the required data structures without needing the hint), but size must still be greater than zero, in order to ensure backward compatibility when new epoll applications are run on older kernels.

Prior to Linux 2.6.29, a /proc/sys/fs/epoll/max_user_instances kernel parameter limited live epolls for each real user ID, and caused epoll_create() to fail with EMFILE on overrun.

## SEE ALSO
close(2), epoll_ctl(2), epoll_wait(2), epoll(7)


title: epoll_ctl(2)

text:
# epoll_ctl(2)

## NAME
epoll_ctl - control interface for an epoll file descriptor

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

## SYNOPSIS

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

```
int epoll_ctl(int epfd, int op, int fd,
              struct epoll_event *_Nullable event);
```

## DESCRIPTION
This system call is used to add, modify, or remove entries in the interest list of the epoll(7) instance referred to by the file descriptor epfd. It requests that the operation op be performed for the target file descriptor, fd.

Valid values for the op argument are:

EPOLL_CTL_ADD

Add an entry to the interest list of the epoll file descriptor, epfd. The entry includes the file descriptor, fd, a reference to the corresponding open file description (see epoll(7) and open(2)), and the settings specified in event.

EPOLL_CTL_MOD

Change the settings associated with fd in the interest list to the new settings specified in event.

EPOLL_CTL_DEL

Remove (deregister) the target file descriptor fd from the interest list. The event argument is ignored and can be NULL (but see BUGS below).

The event argument describes the object linked to the file descriptor fd. The struct epoll_event is described in epoll_event(3type).

The data member of the epoll_event structure specifies data that the kernel should save and then return (via epoll_wait(2)) when this file descriptor becomes ready.

The events member of the epoll_event structure is a bit mask composed by ORing together zero or more event types, returned by epoll_wait(2), and input flags, which affect its behaviour, but aren't returned. The available event types are:

EPOLLIN

The associated file is available for read(2) operations.

EPOLLOUT

The associated file is available for write(2) operations.

EPOLLRDHUP (since Linux 2.6.17)

Stream socket peer closed connection, or shut down writing half of connection. (This flag is especially useful for writing simple code to detect peer shutdown when using edge-triggered monitoring.)

EPOLLPRI

There is an exceptional condition on the file descriptor. See the discussion of POLLPRI in poll(2).

EPOLLERR

Error condition happened on the associated file descriptor. This event is also reported for the write end of a pipe when the read end has been closed.

epoll_wait(2) will always report for this event; it is not necessary to set it in events when calling epoll_ctl().

EPOLLHUP

Hang up happened on the associated file descriptor.

epoll_wait(2) will always wait for this event; it is not necessary to set it in events when calling epoll_ctl().

Note that when reading from a channel such as a pipe or a stream socket, this event merely indicates that the peer closed its end of the channel. Subsequent reads from the channel will return 0 (end of file) only after all outstanding data in the channel has been consumed.

And the available input flags are:

EPOLLET

Requests edge-triggered notification for the associated file descriptor. The default behavior for epoll is level-triggered. See epoll(7) for more detailed information about edge-triggered and level-triggered notification.

EPOLLONESHOT (since Linux 2.6.2)

Requests one-shot notification for the associated file descriptor. This means that after an event notified for the file descriptor by epoll_wait(2), the file descriptor is disabled in the interest list and no other events will be reported by the epoll interface. The user must call epoll_ctl() with EPOLL_CTL_MOD to rearm the file descriptor with a new event mask.

EPOLLWAKEUP (since Linux 3.5)

If EPOLLONESHOT and EPOLLET are clear and the process has the CAP_BLOCK_SUSPEND capability, ensure that the system does not enter "suspend" or "hibernate" while this event is pending or being processed. The event is considered as being "processed" from the time when it is returned by a call to epoll_wait(2) until the next call to epoll_wait(2) on the same epoll(7) file descriptor, the closure of that file descriptor, the removal of the event file descriptor with EPOLL_CTL_DEL, or the clearing of EPOLLWAKEUP for the event file descriptor with EPOLL_CTL_MOD. See also BUGS.

EPOLLEXCLUSIVE (since Linux 4.5)

Sets an exclusive wakeup mode for the epoll file descriptor that is being attached to the target file descriptor, fd. When a wakeup event occurs and multiple epoll file descriptors are attached to the same target file using EPOLLEXCLUSIVE, one or more of the epoll file descriptors will receive an event with epoll_wait(2). The default in this scenario (when EPOLLEXCLUSIVE is not set) is for all epoll file descriptors to receive an event. EPOLLEXCLUSIVE is thus useful for avoiding thundering herd problems in certain scenarios.

If the same file descriptor is in multiple epoll instances, some with the EPOLLEXCLUSIVE flag, and others without, then events will be provided to all epoll instances that did not specify EPOLLEXCLUSIVE, and at least one of the epoll instances that did specify EPOLLEXCLUSIVE.

The following values may be specified in conjunction with EPOLLEXCLUSIVE: EPOLLIN, EPOLLOUT, EPOLLWAKEUP, and EPOLLET. EPOLLHUP and EPOLLERR can also be specified, but this is not required: as usual, these events are always reported if they occur, regardless of whether they are specified in events. Attempts to specify other values in events yield the error EINVAL.

EPOLLEXCLUSIVE may be used only in an EPOLL_CTL_ADD operation; attempts to employ it with EPOLL_CTL_MOD yield an error. If EPOLLEXCLUSIVE has been set using epoll_ctl(), then a subsequent EPOLL_CTL_MOD on the same epfd, fd pair yields an error. A call to epoll_ctl() that specifies EPOLLEXCLUSIVE in events and specifies the target file descriptor fd as an epoll instance will likewise fail. The error in all of these cases is EINVAL.

## RETURN VALUE
When successful, epoll_ctl() returns zero. When an error occurs, epoll_ctl() returns -1 and errno is set to indicate the error.

## ERRORS
EBADF

epfd or fd is not a valid file descriptor.

EEXIST

op was EPOLL_CTL_ADD, and the supplied file descriptor fd is already registered with this epoll instance.

EINVAL

epfd is not an epoll file descriptor, or fd is the same as epfd, or the requested operation op is not supported by this interface.

EINVAL

An invalid event type was specified along with EPOLLEXCLUSIVE in events.

EINVAL

op was EPOLL_CTL_MOD and events included EPOLLEXCLUSIVE.

EINVAL

op was EPOLL_CTL_MOD and the EPOLLEXCLUSIVE flag has previously been applied to this epfd, fd pair.

EINVAL

EPOLLEXCLUSIVE was specified in event and fd refers to an epoll instance.

ELOOP

fd refers to an epoll instance and this EPOLL_CTL_ADD operation would result in a circular loop of epoll instances monitoring one another or a nesting depth of epoll instances greater than 5.

ENOENT

op was EPOLL_CTL_MOD or EPOLL_CTL_DEL, and fd is not registered with this epoll instance.

ENOMEM

There was insufficient memory to handle the requested op control operation.

ENOSPC

The limit imposed by /proc/sys/fs/epoll/max_user_watches was encountered while trying to register (EPOLL_CTL_ADD) a new file descriptor on an epoll instance. See epoll(7) for further details.

EPERM

The target file fd does not support epoll. This error can occur if fd refers to, for example, a regular file or a directory.

## STANDARDS
Linux.

## HISTORY
Linux 2.6, glibc 2.3.2.

## NOTES
The epoll interface supports all file descriptors that support poll(2).

## BUGS
Before Linux 2.6.9, the EPOLL_CTL_DEL operation required a non-null pointer in event, even though this argument is ignored. Since Linux 2.6.9, event can be specified as NULL when using EPOLL_CTL_DEL. Applications that need to be portable to kernels before Linux 2.6.9 should specify a non-null pointer in event.

If EPOLLWAKEUP is specified in flags, but the caller does not have the CAP_BLOCK_SUSPEND capability, then the EPOLLWAKEUP flag is silently ignored. This unfortunate behavior is necessary because no validity checks were performed on the flags argument in the original implementation, and the addition of the EPOLLWAKEUP with a check that caused the call to fail if the caller did not have the CAP_BLOCK_SUSPEND capability caused a breakage in at least one existing user-space application that happened to randomly (and uselessly) specify this bit. A robust application should therefore double check that it has the CAP_BLOCK_SUSPEND capability if attempting to use the EPOLLWAKEUP flag.

## SEE ALSO
epoll_create(2), epoll_wait(2), poll(2), epoll(7)


title: epoll_wait(2)

text:
# epoll_wait(2)

## NAME
epoll_wait, epoll_pwait, epoll_pwait2 - wait for an I/O event on an epoll file descriptor

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

## SYNOPSIS

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

```
int epoll_wait(int epfd, struct epoll_event *events,
               int maxevents, int timeout);
int epoll_pwait(int epfd, struct epoll_event *events,
               int maxevents, int timeout,
               const sigset_t *_Nullable sigmask);
int epoll_pwait2(int epfd, struct epoll_event *events,
               int maxevents, const struct timespec *_Nullable timeout,
               const sigset_t *_Nullable sigmask);
```

## DESCRIPTION
The epoll_wait() system call waits for events on the epoll(7) instance referred to by the file descriptor epfd. The buffer pointed to by events is used to return information from the ready list about file descriptors in the interest list that have some events available. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero.

The timeout argument specifies the number of milliseconds that epoll_wait() will block. Time is measured against the CLOCK_MONOTONIC clock.

A call to epoll_wait() will block until either:

•

a file descriptor delivers an event;

•

the call is interrupted by a signal handler; or

•

the timeout expires.

Note that the timeout interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount. Specifying a timeout of -1 causes epoll_wait() to block indefinitely, while specifying a timeout equal to zero cause epoll_wait() to return immediately, even if no events are available.

The struct epoll_event is described in epoll_event(3type).

The data field of each returned epoll_event structure contains the same data as was specified in the most recent call to epoll_ctl(2) (EPOLL_CTL_ADD, EPOLL_CTL_MOD) for the corresponding open file descriptor.

The events field is a bit mask that indicates the events that have occurred for the corresponding open file description. See epoll_ctl(2) for a list of the bits that may appear in this mask.

### epoll_pwait()
The relationship between epoll_wait() and epoll_pwait() is analogous to the relationship between select(2) and pselect(2): like pselect(2), epoll_pwait() allows an application to safely wait until either a file descriptor becomes ready or until a signal is caught.

The following epoll_pwait() call:

```
ready = epoll_pwait(epfd, &events, maxevents, timeout, &sigmask);
```

is equivalent to atomically executing the following calls:

```
sigset_t origmask;
pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);
ready = epoll_wait(epfd, &events, maxevents, timeout);
pthread_sigmask(SIG_SETMASK, &origmask, NULL);
```

The sigmask argument may be specified as NULL, in which case epoll_pwait() is equivalent to epoll_wait().

### epoll_pwait2()
The epoll_pwait2() system call is equivalent to epoll_pwait() except for the timeout argument. It takes an argument of type timespec to be able to specify nanosecond resolution timeout. This argument functions the same as in pselect(2) and ppoll(2). If timeout is NULL, then epoll_pwait2() can block indefinitely.

## RETURN VALUE
On success, epoll_wait() returns the number of file descriptors ready for the requested I/O, or zero if no file descriptor became ready during the requested timeout milliseconds. On failure, epoll_wait() returns -1 and errno is set to indicate the error.

## ERRORS
EBADF

epfd is not a valid file descriptor.

EFAULT

The memory area pointed to by events is not accessible with write permissions.

EINTR

The call was interrupted by a signal handler before either (1) any of the requested events occurred or (2) the timeout expired; see signal(7).

EINVAL

epfd is not an epoll file descriptor, or maxevents is less than or equal to zero.

## STANDARDS
Linux.

## HISTORY
epoll_wait()

Linux 2.6, glibc 2.3.2.

epoll_pwait()

Linux 2.6.19, glibc 2.6.

epoll_pwait2()

Linux 5.11.

## NOTES
While one thread is blocked in a call to epoll_wait(), it is possible for another thread to add a file descriptor to the waited-upon epoll instance. If the new file descriptor becomes ready, it will cause the epoll_wait() call to unblock.

If more than maxevents file descriptors are ready when epoll_wait() is called, then successive epoll_wait() calls will round robin through the set of ready file descriptors. This behavior helps avoid starvation scenarios, where a process fails to notice that additional file descriptors are ready because it focuses on a set of file descriptors that are already known to be ready.

Note that it is possible to call epoll_wait() on an epoll instance whose interest list is currently empty (or whose interest list becomes empty because file descriptors are closed or removed from the interest in another thread). The call will block until some file descriptor is later added to the interest list (in another thread) and that file descriptor becomes ready.

### C library/kernel differences
The raw epoll_pwait() and epoll_pwait2() system calls have a sixth argument, size_t sigsetsize, which specifies the size in bytes of the sigmask argument. The glibc epoll_pwait() wrapper function specifies this argument as a fixed value (equal to sizeof(sigset_t)).

## BUGS
Before Linux 2.6.37, a timeout value larger than approximately LONG_MAX / HZ milliseconds is treated as -1 (i.e., infinity). Thus, for example, on a system where sizeof(long) is 4 and the kernel HZ value is 1000, this means that timeouts greater than 35.79 minutes are treated as infinity.

## SEE ALSO
epoll_create(2), epoll_ctl(2), epoll(7)