eventfd

title: eventfd(2)

text:
# eventfd(2)

## NAME
eventfd - create a file descriptor for event notification

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

## SYNOPSIS

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

```
int eventfd(unsigned int initval, int flags);
```

## DESCRIPTION
eventfd() creates an "eventfd object" that can be used as an event wait/notify mechanism by user-space applications, and by the kernel to notify user-space applications of events. The object contains an unsigned 64-bit integer (uint64_t) counter that is maintained by the kernel. This counter is initialized with the value specified in the argument initval.

As its return value, eventfd() returns a new file descriptor that can be used to refer to the eventfd object.

The following values may be bitwise ORed in flags to change the behavior of eventfd():

EFD_CLOEXEC (since Linux 2.6.27)

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.

EFD_NONBLOCK (since Linux 2.6.27)

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

EFD_SEMAPHORE (since Linux 2.6.30)

Provide semaphore-like semantics for reads from the new file descriptor. See below.

Up to Linux 2.6.26, the flags argument is unused, and must be specified as zero.

The following operations can be performed on the file descriptor returned by eventfd():

read(2)

Each successful read(2) returns an 8-byte integer. A read(2) fails with the error EINVAL if the size of the supplied buffer is less than 8 bytes.

The value returned by read(2) is in host byte order—that is, the native byte order for integers on the host machine.

The semantics of read(2) depend on whether the eventfd counter currently has a nonzero value and whether the EFD_SEMAPHORE flag was specified when creating the eventfd file descriptor:

•

If EFD_SEMAPHORE was not specified and the eventfd counter has a nonzero value, then a read(2) returns 8 bytes containing that value, and the counter's value is reset to zero.

•

If EFD_SEMAPHORE was specified and the eventfd counter has a nonzero value, then a read(2) returns 8 bytes containing the value 1, and the counter's value is decremented by 1.

•

If the eventfd counter is zero at the time of the call to read(2), then the call either blocks until the counter becomes nonzero (at which time, the read(2) proceeds as described above) or fails with the error EAGAIN if the file descriptor has been made nonblocking.

write(2)

A write(2) call adds the 8-byte integer value supplied in its buffer to the counter. The maximum value that may be stored in the counter is the largest unsigned 64-bit value minus 1 (i.e., 0xfffffffffffffffe). If the addition would cause the counter's value to exceed the maximum, then the write(2) either blocks until a read(2) is performed on the file descriptor, or fails with the error EAGAIN if the file descriptor has been made nonblocking.

A write(2) fails with the error EINVAL if the size of the supplied buffer is less than 8 bytes, or if an attempt is made to write the value 0xffffffffffffffff.

poll(2), select(2) (and similar)

The returned file descriptor supports poll(2) (and analogously epoll(7)) and select(2), as follows:

•

The file descriptor is readable (the select(2) readfds argument; the poll(2) POLLIN flag) if the counter has a value greater than 0.

•

The file descriptor is writable (the select(2) writefds argument; the poll(2) POLLOUT flag) if it is possible to write a value of at least "1" without blocking.

•

If an overflow of the counter value was detected, then select(2) indicates the file descriptor as being both readable and writable, and poll(2) returns a POLLERR event. As noted above, write(2) can never overflow the counter. However an overflow can occur if 2^64 eventfd "signal posts" were performed by the KAIO subsystem (theoretically possible, but practically unlikely). If an overflow has occurred, then read(2) will return that maximum uint64_t value (i.e., 0xffffffffffffffff).

The eventfd file descriptor also supports the other file-descriptor multiplexing APIs: pselect(2) and ppoll(2).

close(2)

When the file descriptor is no longer required it should be closed. When all file descriptors associated with the same eventfd object have been closed, the resources for object are freed by the kernel.

A copy of the file descriptor created by eventfd() is inherited by the child produced by fork(2). The duplicate file descriptor is associated with the same eventfd object. File descriptors created by eventfd() are preserved across execve(2), unless the close-on-exec flag has been set.

## RETURN VALUE
On success, eventfd() returns a new eventfd file descriptor. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EINVAL

An unsupported value was 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.

ENODEV

Could not mount (internal) anonymous inode device.

ENOMEM

There was insufficient memory to create a new eventfd file descriptor.

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

Interface

Attribute

Value

eventfd ()

Thread safety

MT-Safe

## VERSIONS

### C library/kernel differences
There are two underlying Linux system calls: eventfd() and the more recent eventfd2(). The former system call does not implement a flags argument. The latter system call implements the flags values described above. The glibc wrapper function will use eventfd2() where it is available.

### Additional glibc features
The GNU C library defines an additional type, and two functions that attempt to abstract some of the details of reading and writing on an eventfd file descriptor:

```
typedef uint64_t eventfd_t;
int eventfd_read(int fd, eventfd_t *value);
int eventfd_write(int fd, eventfd_t value);
```

The functions perform the read and write operations on an eventfd file descriptor, returning 0 if the correct number of bytes was transferred, or -1 otherwise.

## STANDARDS
Linux, GNU.

## HISTORY
eventfd()

Linux 2.6.22, glibc 2.8.

eventfd2()

Linux 2.6.27 (see VERSIONS). Since glibc 2.9, the eventfd() wrapper will employ the eventfd2() system call, if it is supported by the kernel.

## NOTES
Applications can use an eventfd file descriptor instead of a pipe (see pipe(2)) in all cases where a pipe is used simply to signal events. The kernel overhead of an eventfd file descriptor is much lower than that of a pipe, and only one file descriptor is required (versus the two required for a pipe).

When used in the kernel, an eventfd file descriptor can provide a bridge from kernel to user space, allowing, for example, functionalities like KAIO (kernel AIO) to signal to a file descriptor that some operation is complete.

A key point about an eventfd file descriptor is that it can be monitored just like any other file descriptor using select(2), poll(2), or epoll(7). This means that an application can simultaneously monitor the readiness of "traditional" files and the readiness of other kernel mechanisms that support the eventfd interface. (Without the eventfd() interface, these mechanisms could not be multiplexed via select(2), poll(2), or epoll(7).)

The current value of an eventfd counter can be viewed via the entry for the corresponding file descriptor in the process's /proc/pid/fdinfo directory. See proc(5) for further details.

## EXAMPLES
The following program creates an eventfd file descriptor and then forks to create a child process. While the parent briefly sleeps, the child writes each of the integers supplied in the program's command-line arguments to the eventfd file descriptor. When the parent has finished sleeping, it reads from the eventfd file descriptor.

The following shell session shows a sample run of the program:

```
$ ./a.out 1 2 4 7 14
Child writing 1 to efd
Child writing 2 to efd
Child writing 4 to efd
Child writing 7 to efd
Child writing 14 to efd
Child completed write loop
Parent about to read
Parent read 28 (0x1c) from efd
```

### Program source

```
#include <err.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/eventfd.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    int       efd;

    uint64_t  u;

    ssize_t   s;

    if (argc < 2) {

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

        exit(EXIT_FAILURE);

    }

    efd = eventfd(0, 0);

    if (efd == -1)

        err(EXIT_FAILURE, "eventfd");

    switch (fork()) {

    case 0:

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

            printf("Child writing %s to efd\n", argv[j]);

            u = strtoull(argv[j], NULL, 0);

                    /* strtoull() allows various bases */

            s = write(efd, &u, sizeof(uint64_t));

            if (s != sizeof(uint64_t))

                err(EXIT_FAILURE, "write");

        }

        printf("Child completed write loop\n");

        exit(EXIT_SUCCESS);

    default:

        sleep(2);

        printf("Parent about to read\n");

        s = read(efd, &u, sizeof(uint64_t));

        if (s != sizeof(uint64_t))

            err(EXIT_FAILURE, "read");

        printf("Parent read %"PRIu64" (%#"PRIx64") from efd\n", u, u);

        exit(EXIT_SUCCESS);

    case -1:

        err(EXIT_FAILURE, "fork");

    }
}
```

## SEE ALSO
futex(2), pipe(2), poll(2), read(2), select(2), signalfd(2), timerfd_create(2), write(2), epoll(7), sem_overview(7)


execve

package: man-pages

title: execve(2)

summary: execute program

text:
# execve(2)

## NAME
execve - execute program

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

## SYNOPSIS

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

```
int execve(const char *pathname, char *const _Nullable argv[],
           char *const _Nullable envp[]);
```

## DESCRIPTION
execve() executes the program referred to by pathname. This causes the program that is currently being run by the calling process to be replaced with a new program, with newly initialized stack, heap, and (initialized and uninitialized) data segments.

pathname must be either a binary executable, or a script starting with a line of the form:

```
#!interpreter [optional-arg]
```

For details of the latter case, see "Interpreter scripts" below.

argv is an array of pointers to strings passed to the new program as its command-line arguments. By convention, the first of these strings (i.e., argv[0]) should contain the filename associated with the file being executed. The argv array must be terminated by a NULL pointer. (Thus, in the new program, argv[argc] will be NULL.)

envp is an array of pointers to strings, conventionally of the form key=value, which are passed as the environment of the new program. The envp array must be terminated by a NULL pointer.

This manual page describes the Linux system call in detail; for an overview of the nomenclature and the many, often preferable, standardised variants of this function provided by libc, including ones that search the PATH environment variable, see exec(3).

The argument vector and environment can be accessed by the new program's main function, when it is defined as:

```
int main(int argc, char *argv[], char *envp[])
```

Note, however, that the use of a third argument to the main function is not specified in POSIX.1; according to POSIX.1, the environment should be accessed via the external variable environ(7).

execve() does not return on success, and the text, initialized data, uninitialized data (bss), and stack of the calling process are overwritten according to the contents of the newly loaded program.

If the current program is being ptraced, a SIGTRAP signal is sent to it after a successful execve().

If the set-user-ID bit is set on the program file referred to by pathname, then the effective user ID of the calling process is changed to that of the owner of the program file. Similarly, if the set-group-ID bit is set on the program file, then the effective group ID of the calling process is set to the group of the program file.

The aforementioned transformations of the effective IDs are not performed (i.e., the set-user-ID and set-group-ID bits are ignored) if any of the following is true:

•

the no_new_privs attribute is set for the calling thread (see prctl(2));

•

the underlying filesystem is mounted nosuid (the MS_NOSUID flag for mount(2)); or

•

the calling process is being ptraced.

The capabilities of the program file (see capabilities(7)) are also ignored if any of the above are true.

The effective user ID of the process is copied to the saved set-user-ID; similarly, the effective group ID is copied to the saved set-group-ID. This copying takes place after any effective ID changes that occur because of the set-user-ID and set-group-ID mode bits.

The process's real UID and real GID, as well as its supplementary group IDs, are unchanged by a call to execve().

If the executable is an a.out dynamically linked binary executable containing shared-library stubs, the Linux dynamic linker ld.so(8) is called at the start of execution to bring needed shared objects into memory and link the executable with them.

If the executable is a dynamically linked ELF executable, the interpreter named in the PT_INTERP segment is used to load the needed shared objects. This interpreter is typically /lib/ld-linux.so.2 for binaries linked with glibc (see ld-linux.so(8)).

### Effect on process attributes
All process attributes are preserved during an execve(), except the following:

•

The dispositions of any signals that are being caught are reset to the default (signal(7)).

•

Any alternate signal stack is not preserved (sigaltstack(2)).

•

Memory mappings are not preserved (mmap(2)).

•

Attached System V shared memory segments are detached (shmat(2)).

•

POSIX shared memory regions are unmapped (shm_open(3)).

•

Open POSIX message queue descriptors are closed (mq_overview(7)).

•

Any open POSIX named semaphores are closed (sem_overview(7)).

•

POSIX timers are not preserved (timer_create(2)).

•

Any open directory streams are closed (opendir(3)).

•

Memory locks are not preserved (mlock(2), mlockall(2)).

•

Exit handlers are not preserved (atexit(3), on_exit(3)).

•

The floating-point environment is reset to the default (see fenv(3)).

The process attributes in the preceding list are all specified in POSIX.1. The following Linux-specific process attributes are also not preserved during an execve():

•

The process's "dumpable" attribute is set to the value 1, unless a set-user-ID program, a set-group-ID program, or a program with capabilities is being executed, in which case the dumpable flag may instead be reset to the value in /proc/sys/fs/suid_dumpable, in the circumstances described under PR_SET_DUMPABLE in prctl(2). Note that changes to the "dumpable" attribute may cause ownership of files in the process's /proc/pid directory to change to root:root, as described in proc(5).

•

The prctl(2) PR_SET_KEEPCAPS flag is cleared.

•

(Since Linux 2.4.36 / 2.6.23) If a set-user-ID or set-group-ID program is being executed, then the parent death signal set by prctl(2) PR_SET_PDEATHSIG flag is cleared.

•

The process name, as set by prctl(2) PR_SET_NAME (and displayed by ps -o comm), is reset to the name of the new executable file.

•

The SECBIT_KEEP_CAPS securebits flag is cleared. See capabilities(7).

•

The termination signal is reset to SIGCHLD (see clone(2)).

•

The file descriptor table is unshared, undoing the effect of the CLONE_FILES flag of clone(2).

Note the following further points:

•

All threads other than the calling thread are destroyed during an execve(). Mutexes, condition variables, and other pthreads objects are not preserved.

•

The equivalent of setlocale(LC_ALL, "C") is executed at program start-up.

•

POSIX.1 specifies that the dispositions of any signals that are ignored or set to the default are left unchanged. POSIX.1 specifies one exception: if SIGCHLD is being ignored, then an implementation may leave the disposition unchanged or reset it to the default; Linux does the former.

•

Any outstanding asynchronous I/O operations are canceled (aio_read(3), aio_write(3)).

•

For the handling of capabilities during execve(), see capabilities(7).

•

By default, file descriptors remain open across an execve(). File descriptors that are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2). (If a file descriptor is closed, this will cause the release of all record locks obtained on the underlying file by this process. See fcntl(2) for details.) POSIX.1 says that if file descriptors 0, 1, and 2 would otherwise be closed after a successful execve(), and the process would gain privilege because the set-user-ID or set-group-ID mode bit was set on the executed file, then the system may open an unspecified file for each of these file descriptors. As a general principle, no portable program, whether privileged or not, can assume that these three file descriptors will remain closed across an execve().

### Interpreter scripts
An interpreter script is a text file that has execute permission enabled and whose first line is of the form:

```
#!interpreter [optional-arg]
```

The interpreter must be a valid pathname for an executable file.

If the pathname argument of execve() specifies an interpreter script, then interpreter will be invoked with the following arguments:

```
interpreter [optional-arg] pathname arg...
```

where pathname is the pathname of the file specified as the first argument of execve(), and arg... is the series of words pointed to by the argv argument of execve(), starting at argv[1]. Note that there is no way to get the argv[0] that was passed to the execve() call.

For portable use, optional-arg should either be absent, or be specified as a single word (i.e., it should not contain white space); see NOTES below.

Since Linux 2.6.28, the kernel permits the interpreter of a script to itself be a script. This permission is recursive, up to a limit of four recursions, so that the interpreter may be a script which is interpreted by a script, and so on.

### Limits on size of arguments and environment
Most UNIX implementations impose some limit on the total size of the command-line argument (argv) and environment (envp) strings that may be passed to a new program. POSIX.1 allows an implementation to advertise this limit using the ARG_MAX constant (either defined in <limits.h> or available at run time using the call sysconf(_SC_ARG_MAX)).

Before Linux 2.6.23, the memory used to store the environment and argument strings was limited to 32 pages (defined by the kernel constant MAX_ARG_PAGES). On architectures with a 4-kB page size, this yields a maximum size of 128 kB.

On Linux 2.6.23 and later, most architectures support a size limit derived from the soft RLIMIT_STACK resource limit (see getrlimit(2)) that is in force at the time of the execve() call. (Architectures with no memory management unit are excepted: they maintain the limit that was in effect before Linux 2.6.23.) This change allows programs to have a much larger argument and/or environment list. For these architectures, the total size is limited to 1/4 of the allowed stack size. (Imposing the 1/4-limit ensures that the new program always has some stack space.) Additionally, the total size is limited to 3/4 of the value of the kernel constant _STK_LIM (8 MiB). Since Linux 2.6.25, the kernel also places a floor of 32 pages on this size limit, so that, even when RLIMIT_STACK is set very low, applications are guaranteed to have at least as much argument and environment space as was provided by Linux 2.6.22 and earlier. (This guarantee was not provided in Linux 2.6.23 and 2.6.24.) Additionally, the limit per string is 32 pages (the kernel constant MAX_ARG_STRLEN), and the maximum number of strings is 0x7FFFFFFF.

## RETURN VALUE
On success, execve() does not return, on error -1 is returned, and errno is set to indicate the error.

## ERRORS
E2BIG

The total number of bytes in the environment (envp) and argument list (argv) is too large.

EACCES

Search permission is denied on a component of the path prefix of pathname or the name of a script interpreter. (See also path_resolution(7).)

EACCES

The file or a script interpreter is not a regular file.

EACCES

Execute permission is denied for the file or a script or ELF interpreter.

EACCES

The filesystem is mounted noexec.

EAGAIN (since Linux 3.1)

Having changed its real UID using one of the set*uid() calls, the caller was—and is now still—above its RLIMIT_NPROC resource limit (see setrlimit(2)). For a more detailed explanation of this error, see NOTES.

EFAULT

pathname or one of the pointers in the vectors argv or envp points outside your accessible address space.

EINVAL

An ELF executable had more than one PT_INTERP segment (i.e., tried to name more than one interpreter).

EIO

An I/O error occurred.

EISDIR

An ELF interpreter was a directory.

ELIBBAD

An ELF interpreter was not in a recognized format.

ELOOP

Too many symbolic links were encountered in resolving pathname or the name of a script or ELF interpreter.

ELOOP

The maximum recursion limit was reached during recursive script interpretation (see "Interpreter scripts", above). Before Linux 3.8, the error produced for this case was ENOEXEC.

EMFILE

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

ENAMETOOLONG

pathname is too long.

ENFILE

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

ENOENT

The file pathname or a script or ELF interpreter does not exist.

ENOEXEC

An executable is not in a recognized format, is for the wrong architecture, or has some other format error that means it cannot be executed.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of the path prefix of pathname or a script or ELF interpreter is not a directory.

EPERM

The filesystem is mounted nosuid, the user is not the superuser, and the file has the set-user-ID or set-group-ID bit set.

EPERM

The process is being traced, the user is not the superuser and the file has the set-user-ID or set-group-ID bit set.

EPERM

A "capability-dumb" applications would not obtain the full set of permitted capabilities granted by the executable file. See capabilities(7).

ETXTBSY

The specified executable was open for writing by one or more processes.

## VERSIONS
POSIX does not document the #! behavior, but it exists (with some variations) on other UNIX systems.

On Linux, argv and envp can be specified as NULL. In both cases, this has the same effect as specifying the argument as a pointer to a list containing a single null pointer. Do not take advantage of this nonstandard and nonportable misfeature! On many other UNIX systems, specifying argv as NULL will result in an error (EFAULT). Some other UNIX systems treat the envp==NULL case the same as Linux.

POSIX.1 says that values returned by sysconf(3) should be invariant over the lifetime of a process. However, since Linux 2.6.23, if the RLIMIT_STACK resource limit changes, then the value reported by _SC_ARG_MAX will also change, to reflect the fact that the limit on space for holding command-line arguments and environment variables has changed.

### Interpreter scripts
The kernel imposes a maximum length on the text that follows the "#!" characters at the start of a script; characters beyond the limit are ignored. Before Linux 5.1, the limit is 127 characters. Since Linux 5.1, the limit is 255 characters.

The semantics of the optional-arg argument of an interpreter script vary across implementations. On Linux, the entire string following the interpreter name is passed as a single argument to the interpreter, and this string can include white space. However, behavior differs on some other systems. Some systems use the first white space to terminate optional-arg. On some systems, an interpreter script can have multiple arguments, and white spaces in optional-arg are used to delimit the arguments.

Linux (like most other modern UNIX systems) ignores the set-user-ID and set-group-ID bits on scripts.

## STANDARDS
POSIX.1-2008.

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

With UNIX V6, the argument list of an exec() call was ended by 0, while the argument list of main was ended by -1. Thus, this argument list was not directly usable in a further exec() call. Since UNIX V7, both are NULL.

## NOTES
One sometimes sees execve() (and the related functions described in exec(3)) described as "executing a new process" (or similar). This is a highly misleading description: there is no new process; many attributes of the calling process remain unchanged (in particular, its PID). All that execve() does is arrange for an existing process (the calling process) to execute a new program.

Set-user-ID and set-group-ID processes can not be ptrace(2)d.

The result of mounting a filesystem nosuid varies across Linux kernel versions: some will refuse execution of set-user-ID and set-group-ID executables when this would give the user powers they did not have already (and return EPERM), some will just ignore the set-user-ID and set-group-ID bits and exec() successfully.

In most cases where execve() fails, control returns to the original executable image, and the caller of execve() can then handle the error. However, in (rare) cases (typically caused by resource exhaustion), failure may occur past the point of no return: the original executable image has been torn down, but the new image could not be completely built. In such cases, the kernel kills the process with a SIGSEGV (SIGKILL until Linux 3.17) signal.

### execve() and EAGAIN
A more detailed explanation of the EAGAIN error that can occur (since Linux 3.1) when calling execve() is as follows.

The EAGAIN error can occur when a preceding call to setuid(2), setreuid(2), or setresuid(2) caused the real user ID of the process to change, and that change caused the process to exceed its RLIMIT_NPROC resource limit (i.e., the number of processes belonging to the new real UID exceeds the resource limit). From Linux 2.6.0 to Linux 3.0, this caused the set*uid() call to fail. (Before Linux 2.6, the resource limit was not imposed on processes that changed their user IDs.)

Since Linux 3.1, the scenario just described no longer causes the set*uid() call to fail, because it too often led to security holes where buggy applications didn't check the return status and assumed that—if the caller had root privileges—the call would always succeed. Instead, the set*uid() calls now successfully change the real UID, but the kernel sets an internal flag, named PF_NPROC_EXCEEDED, to note that the RLIMIT_NPROC resource limit has been exceeded. If the PF_NPROC_EXCEEDED flag is set and the resource limit is still exceeded at the time of a subsequent execve() call, that call fails with the error EAGAIN. This kernel logic ensures that the RLIMIT_NPROC resource limit is still enforced for the common privileged daemon workflow—namely, fork(2) + set*uid() + execve().

If the resource limit was not still exceeded at the time of the execve() call (because other processes belonging to this real UID terminated between the set*uid() call and the execve() call), then the execve() call succeeds and the kernel clears the PF_NPROC_EXCEEDED process flag. The flag is also cleared if a subsequent call to fork(2) by this process succeeds.

## EXAMPLES
The following program is designed to be execed by the second program below. It just echoes its command-line arguments, one per line.

```
/* myecho.c */
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{

    for (size_t j = 0; j < argc; j++)

        printf("argv[%zu]: %s\n", j, argv[j]);

    exit(EXIT_SUCCESS);
}
```

This program can be used to exec the program named in its command-line argument:

```
/* execve.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    static char *newargv[] = { NULL, "hello", "world", NULL };

    static char *newenviron[] = { NULL };

    if (argc != 2) {

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

        exit(EXIT_FAILURE);

    }

    newargv[0] = argv[1];

    execve(argv[1], newargv, newenviron);

    perror("execve");   /* execve() returns only on error */

    exit(EXIT_FAILURE);
}
```

We can use the second program to exec the first as follows:

```
$ cc myecho.c -o myecho
$ cc execve.c -o execve
$ ./execve ./myecho
argv[0]: ./myecho
argv[1]: hello
argv[2]: world
```

We can also use these programs to demonstrate the use of a script interpreter. To do this we create a script whose "interpreter" is our myecho program:

```
$ cat > script
#!./myecho script-arg
^D
$ chmod +x script
```

We can then use our program to exec the script:

```
$ ./execve ./script
argv[0]: ./myecho
argv[1]: script-arg
argv[2]: ./script
argv[3]: hello
argv[4]: world
```

## SEE ALSO
chmod(2), execveat(2), fork(2), get_robust_list(2), ptrace(2), exec(3), fexecve(3), getauxval(3), getopt(3), system(3), capabilities(7), credentials(7), environ(7), path_resolution(7), ld.so(8)


execveat

title: execveat(2)

text:
# execveat(2)

## NAME
execveat - execute program relative to a directory file descriptor

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

## SYNOPSIS

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

```
int execveat(int dirfd, const char *pathname,
             char *const _Nullable argv[],
             char *const _Nullable envp[],
             int flags);
```

## DESCRIPTION
The execveat() system call executes the program referred to by the combination of dirfd and pathname. It operates in exactly the same way as execve(2), except for the differences described in this manual page.

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

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

If pathname is absolute, then dirfd is ignored.

If pathname is an empty string and the AT_EMPTY_PATH flag is specified, then the file descriptor dirfd specifies the file to be executed (i.e., dirfd refers to an executable file, rather than a directory).

The flags argument is a bit mask that can include zero or more of the following flags:

AT_EMPTY_PATH

If pathname is an empty string, operate on the file referred to by dirfd (which may have been obtained using the open(2) O_PATH flag).

AT_SYMLINK_NOFOLLOW

If the file identified by dirfd and a non-NULL pathname is a symbolic link, then the call fails with the error ELOOP.

## RETURN VALUE
On success, execveat() does not return. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
The same errors that occur for execve(2) can also occur for execveat(). The following additional errors can occur for execveat():

pathname

is relative but dirfd is neither AT_FDCWD nor a valid file descriptor.

EINVAL

Invalid flag specified in flags.

ELOOP

flags includes AT_SYMLINK_NOFOLLOW and the file identified by dirfd and a non-NULL pathname is a symbolic link.

ENOENT

The program identified by dirfd and pathname requires the use of an interpreter program (such as a script starting with "#!"), but the file descriptor dirfd was opened with the O_CLOEXEC flag, with the result that the program file is inaccessible to the launched interpreter. See BUGS.

ENOTDIR

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

## STANDARDS
Linux.

## HISTORY
Linux 3.19, glibc 2.34.

## NOTES
In addition to the reasons explained in openat(2), the execveat() system call is also needed to allow fexecve(3) to be implemented on systems that do not have the /proc filesystem mounted.

When asked to execute a script file, the argv[0] that is passed to the script interpreter is a string of the form /dev/fd/N or /dev/fd/N/P, where N is the number of the file descriptor passed via the dirfd argument. A string of the first form occurs when AT_EMPTY_PATH is employed. A string of the second form occurs when the script is specified via both dirfd and pathname; in this case, P is the value given in pathname.

For the same reasons described in fexecve(3), the natural idiom when using execveat() is to set the close-on-exec flag on dirfd. (But see BUGS.)

## BUGS
The ENOENT error described above means that it is not possible to set the close-on-exec flag on the file descriptor given to a call of the form:

```
execveat(fd, "", argv, envp, AT_EMPTY_PATH);
```

However, the inability to set the close-on-exec flag means that a file descriptor referring to the script leaks through to the script itself. As well as wasting a file descriptor, this leakage can lead to file-descriptor exhaustion in scenarios where scripts recursively employ execveat().

## SEE ALSO
execve(2), openat(2), fexecve(3)


title: exit_group(2)

summary: exit all threads in a process

text:
# exit_group(2)

## NAME
exit_group - exit all threads in a process

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

## SYNOPSIS

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

```
[[noreturn]] void syscall(SYS_exit_group, int status);
```

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

## DESCRIPTION
This system call terminates all threads in the calling process's thread group.

## RETURN VALUE
This system call does not return.

## STANDARDS
Linux.

## HISTORY
Linux 2.5.35.

## NOTES
Since glibc 2.3, this is the system call invoked when the _exit(2) wrapper function is called.

## SEE ALSO
_exit(2)


fallocate

title: fallocate(2)

summary: manipulate file space

text:
# fallocate(2)

## NAME
fallocate - manipulate file space

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

## SYNOPSIS

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

```
int fallocate(int fd, int mode, off_t offset, off_t len);
```

## DESCRIPTION
This is a nonportable, Linux-specific system call. For the portable, POSIX.1-specified method of ensuring that space is allocated for a file, see posix_fallocate(3).

fallocate() allows the caller to directly manipulate the allocated disk space for the file referred to by fd for the byte range starting at offset and continuing for len bytes.

The mode argument determines the operation to be performed on the given range. Details of the supported operations are given in the subsections below.

### Allocating disk space
The default operation (i.e., mode is zero) of fallocate() allocates the disk space within the range specified by offset and len. The file size (as reported by stat(2)) will be changed if offset+len is greater than the file size. Any subregion within the range specified by offset and len that did not contain data before the call will be initialized to zero. This default behavior closely resembles the behavior of the posix_fallocate(3) library function, and is intended as a method of optimally implementing that function.

After a successful call, subsequent writes into the range specified by offset and len are guaranteed not to fail because of lack of disk space.

If the FALLOC_FL_KEEP_SIZE flag is specified in mode, the behavior of the call is similar, but the file size will not be changed even if offset+len is greater than the file size. Preallocating zeroed blocks beyond the end of the file in this manner is useful for optimizing append workloads.

If the FALLOC_FL_UNSHARE_RANGE flag is specified in mode, shared file data extents will be made private to the file to guarantee that a subsequent write will not fail due to lack of space. Typically, this will be done by performing a copy-on-write operation on all shared data in the file. This flag may not be supported by all filesystems.

Because allocation is done in block size chunks, fallocate() may allocate a larger range of disk space than was specified.

### Deallocating file space
Specifying the FALLOC_FL_PUNCH_HOLE flag (available since Linux 2.6.38) in mode deallocates space (i.e., creates a hole) in the byte range starting at offset and continuing for len bytes. Within the specified range, partial filesystem blocks are zeroed, and whole filesystem blocks are removed from the file. After a successful call, subsequent reads from this range will return zeros.

The FALLOC_FL_PUNCH_HOLE flag must be ORed with FALLOC_FL_KEEP_SIZE in mode; in other words, even when punching off the end of the file, the file size (as reported by stat(2)) does not change.

Not all filesystems support FALLOC_FL_PUNCH_HOLE; if a filesystem doesn't support the operation, an error is returned. The operation is supported on at least the following filesystems:

•

XFS (since Linux 2.6.38)

•

ext4 (since Linux 3.0)

•

Btrfs (since Linux 3.7)

•

tmpfs(5) (since Linux 3.5)

•

gfs2(5) (since Linux 4.16)

### Collapsing file space
Specifying the FALLOC_FL_COLLAPSE_RANGE flag (available since Linux 3.15) in mode removes a byte range from a file, without leaving a hole. The byte range to be collapsed starts at offset and continues for len bytes. At the completion of the operation, the contents of the file starting at the location offset+len will be appended at the location offset, and the file will be len bytes smaller.

A filesystem may place limitations on the granularity of the operation, in order to ensure efficient implementation. Typically, offset and len must be a multiple of the filesystem logical block size, which varies according to the filesystem type and configuration. If a filesystem has such a requirement, fallocate() fails with the error EINVAL if this requirement is violated.

If the region specified by offset plus len reaches or passes the end of file, an error is returned; instead, use ftruncate(2) to truncate a file.

No other flags may be specified in mode in conjunction with FALLOC_FL_COLLAPSE_RANGE.

As at Linux 3.15, FALLOC_FL_COLLAPSE_RANGE is supported by ext4 (only for extent-based files) and XFS.

### Zeroing file space
Specifying the FALLOC_FL_ZERO_RANGE flag (available since Linux 3.15) in mode zeros space in the byte range starting at offset and continuing for len bytes. Within the specified range, blocks are preallocated for the regions that span the holes in the file. After a successful call, subsequent reads from this range will return zeros.

Zeroing is done within the filesystem preferably by converting the range into unwritten extents. This approach means that the specified range will not be physically zeroed out on the device (except for partial blocks at the either end of the range), and I/O is (otherwise) required only to update metadata.

If the FALLOC_FL_KEEP_SIZE flag is additionally specified in mode, the behavior of the call is similar, but the file size will not be changed even if offset+len is greater than the file size. This behavior is the same as when preallocating space with FALLOC_FL_KEEP_SIZE specified.

Not all filesystems support FALLOC_FL_ZERO_RANGE; if a filesystem doesn't support the operation, an error is returned. The operation is supported on at least the following filesystems:

•

XFS (since Linux 3.15)

•

ext4, for extent-based files (since Linux 3.15)

•

SMB3 (since Linux 3.17)

•

Btrfs (since Linux 4.16)

### Increasing file space
Specifying the FALLOC_FL_INSERT_RANGE flag (available since Linux 4.1) in mode increases the file space by inserting a hole within the file size without overwriting any existing data. The hole will start at offset and continue for len bytes. When inserting the hole inside file, the contents of the file starting at offset will be shifted upward (i.e., to a higher file offset) by len bytes. Inserting a hole inside a file increases the file size by len bytes.

This mode has the same limitations as FALLOC_FL_COLLAPSE_RANGE regarding the granularity of the operation. If the granularity requirements are not met, fallocate() fails with the error EINVAL. If the offset is equal to or greater than the end of file, an error is returned. For such operations (i.e., inserting a hole at the end of file), ftruncate(2) should be used.

No other flags may be specified in mode in conjunction with FALLOC_FL_INSERT_RANGE.

FALLOC_FL_INSERT_RANGE requires filesystem support. Filesystems that support this operation include XFS (since Linux 4.1) and ext4 (since Linux 4.2).

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

## ERRORS
EBADF

fd is not a valid file descriptor, or is not opened for writing.

EFBIG

offset+len exceeds the maximum file size.

EFBIG

mode is FALLOC_FL_INSERT_RANGE, and the current file size+len exceeds the maximum file size.

EINTR

A signal was caught during execution; see signal(7).

EINVAL

offset was less than 0, or len was less than or equal to 0.

EINVAL

mode is FALLOC_FL_COLLAPSE_RANGE and the range specified by offset plus len reaches or passes the end of the file.

EINVAL

mode is FALLOC_FL_INSERT_RANGE and the range specified by offset reaches or passes the end of the file.

EINVAL

mode is FALLOC_FL_COLLAPSE_RANGE or FALLOC_FL_INSERT_RANGE, but either offset or len is not a multiple of the filesystem block size.

EINVAL

mode contains one of FALLOC_FL_COLLAPSE_RANGE or FALLOC_FL_INSERT_RANGE and also other flags; no other flags are permitted with FALLOC_FL_COLLAPSE_RANGE or FALLOC_FL_INSERT_RANGE.

EINVAL

mode is FALLOC_FL_COLLAPSE_RANGE, FALLOC_FL_ZERO_RANGE, or FALLOC_FL_INSERT_RANGE, but the file referred to by fd is not a regular file.

EIO

An I/O error occurred while reading from or writing to a filesystem.

ENODEV

fd does not refer to a regular file or a directory. (If fd is a pipe or FIFO, a different error results.)

ENOSPC

There is not enough space left on the device containing the file referred to by fd.

ENOSYS

This kernel does not implement fallocate().

EOPNOTSUPP

The filesystem containing the file referred to by fd does not support this operation; or the mode is not supported by the filesystem containing the file referred to by fd.

EPERM

The file referred to by fd is marked immutable (see chattr(1)).

EPERM

mode specifies FALLOC_FL_PUNCH_HOLE, FALLOC_FL_COLLAPSE_RANGE, or FALLOC_FL_INSERT_RANGE and the file referred to by fd is marked append-only (see chattr(1)).

EPERM

The operation was prevented by a file seal; see fcntl(2).

ESPIPE

fd refers to a pipe or FIFO.

ETXTBSY

mode specifies FALLOC_FL_COLLAPSE_RANGE or FALLOC_FL_INSERT_RANGE, but the file referred to by fd is currently being executed.

## STANDARDS
Linux.

## HISTORY
fallocate()

Linux 2.6.23, glibc 2.10.

FALLOC_FL_*

glibc 2.18.

## SEE ALSO
fallocate(1), ftruncate(2), posix_fadvise(3), posix_fallocate(3)


title: fanotify_init(2)

summary: create and initialize fanotify group

text:
# fanotify_init(2)

## NAME
fanotify_init - create and initialize fanotify group

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

## SYNOPSIS

```
#include <fcntl.h>            /* Definition of O_* constants */
#include <sys/fanotify.h>
```

```
int fanotify_init(unsigned int flags, unsigned int event_f_flags);
```

## DESCRIPTION
For an overview of the fanotify API, see fanotify(7).

fanotify_init() initializes a new fanotify group and returns a file descriptor for the event queue associated with the group.

The file descriptor is used in calls to fanotify_mark(2) to specify the files, directories, mounts, or filesystems for which fanotify events shall be created. These events are received by reading from the file descriptor. Some events are only informative, indicating that a file has been accessed. Other events can be used to determine whether another application is permitted to access a file or directory. Permission to access filesystem objects is granted by writing to the file descriptor.

Multiple programs may be using the fanotify interface at the same time to monitor the same files.

The number of fanotify groups per user is limited. See fanotify(7) for details about this limit.

The flags argument contains a multi-bit field defining the notification class of the listening application and further single bit fields specifying the behavior of the file descriptor.

If multiple listeners for permission events exist, the notification class is used to establish the sequence in which the listeners receive the events.

Only one of the following notification classes may be specified in flags:

FAN_CLASS_PRE_CONTENT

This value allows the receipt of events notifying that a file has been accessed and events for permission decisions if a file may be accessed. It is intended for event listeners that need to access files before they contain their final data. This notification class might be used by hierarchical storage managers, for example. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_CLASS_CONTENT

This value allows the receipt of events notifying that a file has been accessed and events for permission decisions if a file may be accessed. It is intended for event listeners that need to access files when they already contain their final content. This notification class might be used by malware detection programs, for example. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_CLASS_NOTIF

This is the default value. It does not need to be specified. This value only allows the receipt of events notifying that a file has been accessed. Permission decisions before the file is accessed are not possible.

Listeners with different notification classes will receive events in the order FAN_CLASS_PRE_CONTENT, FAN_CLASS_CONTENT, FAN_CLASS_NOTIF. The order of notification for listeners in the same notification class is undefined.

The following bits can additionally be set in flags:

FAN_CLOEXEC

Set the close-on-exec flag (FD_CLOEXEC) on the new file descriptor. See the description of the O_CLOEXEC flag in open(2).

FAN_NONBLOCK

Enable the nonblocking flag (O_NONBLOCK) for the file descriptor. Reading from the file descriptor will not block. Instead, if no data is available, read(2) fails with the error EAGAIN.

FAN_UNLIMITED_QUEUE

Remove the limit on the number of events in the event queue. See fanotify(7) for details about this limit. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_UNLIMITED_MARKS

Remove the limit on the number of fanotify marks per user. See fanotify(7) for details about this limit. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_REPORT_TID (since Linux 4.20)

Report thread ID (TID) instead of process ID (PID) in the pid field of the struct fanotify_event_metadata supplied to read(2) (see fanotify(7)). Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_ENABLE_AUDIT (since Linux 4.15)

Enable generation of audit log records about access mediation performed by permission events. The permission event response has to be marked with the FAN_AUDIT flag for an audit log record to be generated. Use of this flag requires the CAP_AUDIT_WRITE capability.

FAN_REPORT_FID (since Linux 5.1)

This value allows the receipt of events which contain additional information about the underlying filesystem object correlated to an event. An additional record of type FAN_EVENT_INFO_TYPE_FID encapsulates the information about the object and is included alongside the generic event metadata structure. The file descriptor that is used to represent the object correlated to an event is instead substituted with a file handle. It is intended for applications that may find the use of a file handle to identify an object more suitable than a file descriptor. Additionally, it may be used for applications monitoring a directory or a filesystem that are interested in the directory entry modification events FAN_CREATE, FAN_DELETE, FAN_MOVE, and FAN_RENAME, or in events such as FAN_ATTRIB, FAN_DELETE_SELF, and FAN_MOVE_SELF. All the events above require an fanotify group that identifies filesystem objects by file handles. Note that without the flag FAN_REPORT_TARGET_FID, for the directory entry modification events, there is an information record that identifies the modified directory and not the created/deleted/moved child object. The use of FAN_CLASS_CONTENT or FAN_CLASS_PRE_CONTENT is not permitted with this flag and will result in the error EINVAL. See fanotify(7) for additional details.

FAN_REPORT_DIR_FID (since Linux 5.9)

Events for fanotify groups initialized with this flag will contain (see exceptions below) additional information about a directory object correlated to an event. An additional record of type FAN_EVENT_INFO_TYPE_DFID encapsulates the information about the directory object and is included alongside the generic event metadata structure. For events that occur on a non-directory object, the additional structure includes a file handle that identifies the parent directory filesystem object. Note that there is no guarantee that the directory filesystem object will be found at the location described by the file handle information at the time the event is received. When combined with the flag FAN_REPORT_FID, two records may be reported with events that occur on a non-directory object, one to identify the non-directory object itself and one to identify the parent directory object. Note that in some cases, a filesystem object does not have a parent, for example, when an event occurs on an unlinked but open file. In that case, with the FAN_REPORT_FID flag, the event will be reported with only one record to identify the non-directory object itself, because there is no directory associated with the event. Without the FAN_REPORT_FID flag, no event will be reported. See fanotify(7) for additional details.

FAN_REPORT_NAME (since Linux 5.9)

Events for fanotify groups initialized with this flag will contain additional information about the name of the directory entry correlated to an event. This flag must be provided in conjunction with the flag FAN_REPORT_DIR_FID. Providing this flag value without FAN_REPORT_DIR_FID will result in the error EINVAL. This flag may be combined with the flag FAN_REPORT_FID. An additional record of type FAN_EVENT_INFO_TYPE_DFID_NAME, which encapsulates the information about the directory entry, is included alongside the generic event metadata structure and substitutes the additional information record of type FAN_EVENT_INFO_TYPE_DFID. The additional record includes a file handle that identifies a directory filesystem object followed by a name that identifies an entry in that directory. For the directory entry modification events FAN_CREATE, FAN_DELETE, and FAN_MOVE, the reported name is that of the created/deleted/moved directory entry. The event FAN_RENAME may contain two information records. One of type FAN_EVENT_INFO_TYPE_OLD_DFID_NAME identifying the old directory entry, and another of type FAN_EVENT_INFO_TYPE_NEW_DFID_NAME identifying the new directory entry. For other events that occur on a directory object, the reported file handle is that of the directory object itself and the reported name is '.'. For other events that occur on a non-directory object, the reported file handle is that of the parent directory object and the reported name is the name of a directory entry where the object was located at the time of the event. The rationale behind this logic is that the reported directory file handle can be passed to open_by_handle_at(2) to get an open directory file descriptor and that file descriptor along with the reported name can be used to call fstatat(2). The same rule that applies to record type FAN_EVENT_INFO_TYPE_DFID also applies to record type FAN_EVENT_INFO_TYPE_DFID_NAME: if a non-directory object has no parent, either the event will not be reported or it will be reported without the directory entry information. Note that there is no guarantee that the filesystem object will be found at the location described by the directory entry information at the time the event is received. See fanotify(7) for additional details.

FAN_REPORT_DFID_NAME

This is a synonym for (FAN_REPORT_DIR_FID|FAN_REPORT_NAME).

FAN_REPORT_TARGET_FID (since Linux 5.17)

Events for fanotify groups initialized with this flag will contain additional information about the child correlated with directory entry modification events. This flag must be provided in conjunction with the flags FAN_REPORT_FID, FAN_REPORT_DIR_FID and FAN_REPORT_NAME. or else the error EINVAL will be returned. For the directory entry modification events FAN_CREATE, FAN_DELETE, FAN_MOVE, and FAN_RENAME, an additional record of type FAN_EVENT_INFO_TYPE_FID, is reported in addition to the information records of type FAN_EVENT_INFO_TYPE_DFID, FAN_EVENT_INFO_TYPE_DFID_NAME, FAN_EVENT_INFO_TYPE_OLD_DFID_NAME, and FAN_EVENT_INFO_TYPE_NEW_DFID_NAME. The additional record includes a file handle that identifies the filesystem child object that the directory entry is referring to.

FAN_REPORT_DFID_NAME_TARGET

This is a synonym for (FAN_REPORT_DFID_NAME|FAN_REPORT_FID|FAN_REPORT_TARGET_FID).

FAN_REPORT_PIDFD (since Linux 5.15)

Events for fanotify groups initialized with this flag will contain an additional information record alongside the generic fanotify_event_metadata structure. This information record will be of type FAN_EVENT_INFO_TYPE_PIDFD and will contain a pidfd for the process that was responsible for generating an event. A pidfd returned in this information record object is no different to the pidfd that is returned when calling pidfd_open(2). Usage of this information record are for applications that may be interested in reliably determining whether the process responsible for generating an event has been recycled or terminated. The use of the FAN_REPORT_TID flag along with FAN_REPORT_PIDFD is currently not supported and attempting to do so will result in the error EINVAL being returned. This limitation is currently imposed by the pidfd API as it currently only supports the creation of pidfds for thread-group leaders. Creating pidfds for non-thread-group leaders may be supported at some point in the future, so this restriction may eventually be lifted. For more details on information records, see fanotify(7).

The event_f_flags argument defines the file status flags that will be set on the open file descriptions that are created for fanotify events. For details of these flags, see the description of the flags values in open(2). event_f_flags includes a multi-bit field for the access mode. This field can take the following values:

O_RDONLY

This value allows only read access.

O_WRONLY

This value allows only write access.

O_RDWR

This value allows read and write access.

Additional bits can be set in event_f_flags. The most useful values are:

O_LARGEFILE

Enable support for files exceeding 2 GB. Failing to set this flag will result in an EOVERFLOW error when trying to open a large file which is monitored by an fanotify group on a 32-bit system.

O_CLOEXEC (since Linux 3.18)

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

The following are also allowable: O_APPEND, O_DSYNC, O_NOATIME, O_NONBLOCK, and O_SYNC. Specifying any other flag in event_f_flags yields the error EINVAL (but see BUGS).

## RETURN VALUE
On success, fanotify_init() returns a new file descriptor. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

An invalid value was passed in flags or event_f_flags. FAN_ALL_INIT_FLAGS (deprecated since Linux 4.20) defines all allowable bits for flags.

EMFILE

The number of fanotify groups for this user exceeds the limit. See fanotify(7) for details about this limit.

EMFILE

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

ENOMEM

The allocation of memory for the notification group failed.

ENOSYS

This kernel does not implement fanotify_init(). The fanotify API is available only if the kernel was configured with CONFIG_FANOTIFY.

EPERM

The operation is not permitted because the caller lacks a required capability.

## VERSIONS
Prior to Linux 5.13, calling fanotify_init() required the CAP_SYS_ADMIN capability. Since Linux 5.13, users may call fanotify_init() without the CAP_SYS_ADMIN capability to create and initialize an fanotify group with limited functionality.

The limitations imposed on an event listener created by a user without the

CAP_SYS_ADMIN capability are as follows:

•

The user cannot request for an unlimited event queue by using FAN_UNLIMITED_QUEUE.

•

The user cannot request for an unlimited number of marks by using FAN_UNLIMITED_MARKS.

•

The user cannot request to use either notification classes FAN_CLASS_CONTENT or FAN_CLASS_PRE_CONTENT. This means that user cannot request permission events.

•

The user is required to create a group that identifies filesystem objects by file handles, for example, by providing the FAN_REPORT_FID flag.

•

The user is limited to only mark inodes. The ability to mark a mount or filesystem via fanotify_mark() through the use of FAN_MARK_MOUNT or FAN_MARK_FILESYSTEM is not permitted.

•

The event object in the event queue is limited in terms of the information that is made available to the unprivileged user. A user will also not receive the pid that generated the event, unless the listening process itself generated the event.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.37.

## BUGS
The following bug was present before Linux 3.18:

•

The O_CLOEXEC is ignored when passed in event_f_flags.

The following bug was present before Linux 3.14:

•

The event_f_flags argument is not checked for invalid flags. Flags that are intended only for internal use, such as FMODE_EXEC, can be set, and will consequently be set for the file descriptors returned when reading from the fanotify file descriptor.

## SEE ALSO
fanotify_mark(2), fanotify(7)


title: fanotify_mark(2)

text:
# fanotify_mark(2)

## NAME
fanotify_mark - add, remove, or modify an fanotify mark on a filesystem object

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

## SYNOPSIS

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

```
int fanotify_mark(int fanotify_fd, unsigned int flags,
                  uint64_t mask, int dirfd,
                  const char *_Nullable pathname);
```

## DESCRIPTION
For an overview of the fanotify API, see fanotify(7).

fanotify_mark() adds, removes, or modifies an fanotify mark on a filesystem object. The caller must have read permission on the filesystem object that is to be marked.

The fanotify_fd argument is a file descriptor returned by fanotify_init(2).

flags is a bit mask describing the modification to perform. It must include exactly one of the following values:

FAN_MARK_ADD

The events in mask will be added to the mark mask (or to the ignore mask). mask must be nonempty or the error EINVAL will occur.

FAN_MARK_REMOVE

The events in argument mask will be removed from the mark mask (or from the ignore mask). mask must be nonempty or the error EINVAL will occur.

FAN_MARK_FLUSH

Remove either all marks for filesystems, all marks for mounts, or all marks for directories and files from the fanotify group. If flags contains FAN_MARK_MOUNT, all marks for mounts are removed from the group. If flags contains FAN_MARK_FILESYSTEM, all marks for filesystems are removed from the group. Otherwise, all marks for directories and files are removed. No flag other than, and at most one of, the flags FAN_MARK_MOUNT or FAN_MARK_FILESYSTEM can be used in conjunction with FAN_MARK_FLUSH. mask is ignored.

If none of the values above is specified, or more than one is specified, the call fails with the error EINVAL.

In addition, zero or more of the following values may be ORed into flags:

FAN_MARK_DONT_FOLLOW

If pathname is a symbolic link, mark the link itself, rather than the file to which it refers. (By default, fanotify_mark() dereferences pathname if it is a symbolic link.)

FAN_MARK_ONLYDIR

If the filesystem object to be marked is not a directory, the error ENOTDIR shall be raised.

FAN_MARK_MOUNT

Mark the mount specified by pathname. If pathname is not itself a mount point, the mount containing pathname will be marked. All directories, subdirectories, and the contained files of the mount will be monitored. The events which require that filesystem objects are identified by file handles, such as FAN_CREATE, FAN_ATTRIB, FAN_MOVE, and FAN_DELETE_SELF, cannot be provided as a mask when flags contains FAN_MARK_MOUNT. Attempting to do so will result in the error EINVAL being returned. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_MARK_FILESYSTEM (since Linux 4.20)

Mark the filesystem specified by pathname. The filesystem containing pathname will be marked. All the contained files and directories of the filesystem from any mount point will be monitored. Use of this flag requires the CAP_SYS_ADMIN capability.

FAN_MARK_IGNORED_MASK

The events in mask shall be added to or removed from the ignore mask. Note that the flags FAN_ONDIR, and FAN_EVENT_ON_CHILD have no effect when provided with this flag. The effect of setting the flags FAN_ONDIR, and FAN_EVENT_ON_CHILD in the mark mask on the events that are set in the ignore mask is undefined and depends on the Linux kernel version. Specifically, prior to Linux 5.9, setting a mark mask on a file and a mark with ignore mask on its parent directory would not result in ignoring events on the file, regardless of the FAN_EVENT_ON_CHILD flag in the parent directory's mark mask. When the ignore mask is updated with the FAN_MARK_IGNORED_MASK flag on a mark that was previously updated with the FAN_MARK_IGNORE flag, the update fails with EEXIST error.

FAN_MARK_IGNORE (since Linux 6.0)

This flag has a similar effect as setting the FAN_MARK_IGNORED_MASK flag. The events in mask shall be added to or removed from the ignore mask. Unlike the FAN_MARK_IGNORED_MASK flag, this flag also has the effect that the FAN_ONDIR, and FAN_EVENT_ON_CHILD flags take effect on the ignore mask. Specifically, unless the FAN_ONDIR flag is set with FAN_MARK_IGNORE, events on directories will not be ignored. If the flag FAN_EVENT_ON_CHILD is set with FAN_MARK_IGNORE, events on children will be ignored. For example, a mark on a directory with combination of a mask with FAN_CREATE event and FAN_ONDIR flag and an ignore mask with FAN_CREATE event and without FAN_ONDIR flag, will result in getting only the events for creation of sub-directories. When using the FAN_MARK_IGNORE flag to add to an ignore mask of a mount, filesystem, or directory inode mark, the FAN_MARK_IGNORED_SURV_MODIFY flag must be specified. Failure to do so will results with EINVAL or EISDIR error.

FAN_MARK_IGNORED_SURV_MODIFY

The ignore mask shall survive modify events. If this flag is not set, the ignore mask is cleared when a modify event occurs on the marked object. Omitting this flag is typically used to suppress events (e.g., FAN_OPEN) for a specific file, until that specific file's content has been modified. It is far less useful to suppress events on an entire filesystem, or mount, or on all files inside a directory, until some file's content has been modified. For this reason, the FAN_MARK_IGNORE flag requires the FAN_MARK_IGNORED_SURV_MODIFY flag on a mount, filesystem, or directory inode mark. This flag cannot be removed from a mark once set. When the ignore mask is updated without this flag on a mark that was previously updated with the FAN_MARK_IGNORE and FAN_MARK_IGNORED_SURV_MODIFY flags, the update fails with EEXIST error.

FAN_MARK_IGNORE_SURV

This is a synonym for (FAN_MARK_IGNORE|FAN_MARK_IGNORED_SURV_MODIFY).

FAN_MARK_EVICTABLE (since Linux 5.19)

When an inode mark is created with this flag, the inode object will not be pinned to the inode cache, therefore, allowing the inode object to be evicted from the inode cache when the memory pressure on the system is high. The eviction of the inode object results in the evictable mark also being lost. When the mask of an evictable inode mark is updated without using the FAN_MARK_EVICATBLE flag, the marked inode is pinned to inode cache and the mark is no longer evictable. When the mask of a non-evictable inode mark is updated with the FAN_MARK_EVICTABLE flag, the inode mark remains non-evictable and the update fails with EEXIST error. Mounts and filesystems are not evictable objects, therefore, an attempt to create a mount mark or a filesystem mark with the FAN_MARK_EVICTABLE flag, will result in the error EINVAL. For example, inode marks can be used in combination with mount marks to reduce the amount of events from noninteresting paths. The event listener reads events, checks if the path reported in the event is of interest, and if it is not, the listener sets a mark with an ignore mask on the directory. Evictable inode marks allow using this method for a large number of directories without the concern of pinning all inodes and exhausting the system's memory.

mask defines which events shall be listened for (or which shall be ignored). It is a bit mask composed of the following values:

FAN_ACCESS

Create an event when a file or directory (but see BUGS) is accessed (read).

FAN_MODIFY

Create an event when a file is modified (write).

FAN_CLOSE_WRITE

Create an event when a writable file is closed.

FAN_CLOSE_NOWRITE

Create an event when a read-only file or directory is closed.

FAN_OPEN

Create an event when a file or directory is opened.

FAN_OPEN_EXEC (since Linux 5.0)

Create an event when a file is opened with the intent to be executed. See NOTES for additional details.

FAN_ATTRIB (since Linux 5.1)

Create an event when the metadata for a file or directory has changed. An fanotify group that identifies filesystem objects by file handles is required.

FAN_CREATE (since Linux 5.1)

Create an event when a file or directory has been created in a marked parent directory. An fanotify group that identifies filesystem objects by file handles is required.

FAN_DELETE (since Linux 5.1)

Create an event when a file or directory has been deleted in a marked parent directory. An fanotify group that identifies filesystem objects by file handles is required.

FAN_DELETE_SELF (since Linux 5.1)

Create an event when a marked file or directory itself is deleted. An fanotify group that identifies filesystem objects by file handles is required.

FAN_FS_ERROR (since Linux 5.16)

Create an event when a filesystem error leading to inconsistent filesystem metadata is detected. An additional information record of type FAN_EVENT_INFO_TYPE_ERROR is returned for each event in the read buffer. An fanotify group that identifies filesystem objects by file handles is required.

Events of such type are dependent on support from the underlying filesystem. At the time of writing, only the ext4 filesystem reports FAN_FS_ERROR events.

See fanotify(7) for additional details.

FAN_MOVED_FROM (since Linux 5.1)

Create an event when a file or directory has been moved from a marked parent directory. An fanotify group that identifies filesystem objects by file handles is required.

FAN_MOVED_TO (since Linux 5.1)

Create an event when a file or directory has been moved to a marked parent directory. An fanotify group that identifies filesystem objects by file handles is required.

FAN_RENAME (since Linux 5.17)

This event contains the same information provided by events FAN_MOVED_FROM and FAN_MOVED_TO, however is represented by a single event with up to two information records. An fanotify group that identifies filesystem objects by file handles is required. If the filesystem object to be marked is not a directory, the error ENOTDIR shall be raised.

FAN_MOVE_SELF (since Linux 5.1)

Create an event when a marked file or directory itself has been moved. An fanotify group that identifies filesystem objects by file handles is required.

FAN_OPEN_PERM

Create an event when a permission to open a file or directory is requested. An fanotify file descriptor created with FAN_CLASS_PRE_CONTENT or FAN_CLASS_CONTENT is required.

FAN_OPEN_EXEC_PERM (since Linux 5.0)

Create an event when a permission to open a file for execution is requested. An fanotify file descriptor created with FAN_CLASS_PRE_CONTENT or FAN_CLASS_CONTENT is required. See NOTES for additional details.

FAN_ACCESS_PERM

Create an event when a permission to read a file or directory is requested. An fanotify file descriptor created with FAN_CLASS_PRE_CONTENT or FAN_CLASS_CONTENT is required.

FAN_ONDIR

Create events for directories—for example, when opendir(3), readdir(3) (but see BUGS), and closedir(3) are called. Without this flag, events are created only for files. In the context of directory entry events, such as FAN_CREATE, FAN_DELETE, FAN_MOVED_FROM, and FAN_MOVED_TO, specifying the flag FAN_ONDIR is required in order to create events when subdirectory entries are modified (i.e., mkdir(2)/ rmdir(2)).

FAN_EVENT_ON_CHILD

Events for the immediate children of marked directories shall be created. The flag has no effect when marking mounts and filesystems. Note that events are not generated for children of the subdirectories of marked directories. More specifically, the directory entry modification events FAN_CREATE, FAN_DELETE, FAN_MOVED_FROM, and FAN_MOVED_TO are not generated for any entry modifications performed inside subdirectories of marked directories. Note that the events FAN_DELETE_SELF and FAN_MOVE_SELF are not generated for children of marked directories. To monitor complete directory trees it is necessary to mark the relevant mount or filesystem.

The following composed values are defined:

FAN_CLOSE

A file is closed (FAN_CLOSE_WRITE|FAN_CLOSE_NOWRITE).

FAN_MOVE

A file or directory has been moved (FAN_MOVED_FROM|FAN_MOVED_TO).

The filesystem object to be marked is determined by the file descriptor dirfd and the pathname specified in pathname:

•

If pathname is NULL, dirfd defines the filesystem object to be marked.

•

If pathname is NULL, and dirfd takes the special value AT_FDCWD, the current working directory is to be marked.

•

If pathname is absolute, it defines the filesystem object to be marked, and dirfd is ignored.

•

If pathname is relative, and dirfd does not have the value AT_FDCWD, then the filesystem object to be marked is determined by interpreting pathname relative the directory referred to by dirfd.

•

If pathname is relative, and dirfd has the value AT_FDCWD, then the filesystem object to be marked is determined by interpreting pathname relative to the current working directory. (See openat(2) for an explanation of why the dirfd argument is useful.)

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

## ERRORS
EBADF

An invalid file descriptor was passed in fanotify_fd.

EBADF

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

EEXIST

The filesystem object indicated by dirfd and pathname has a mark that was updated without the FAN_MARK_EVICTABLE flag, and the user attempted to update the mark with FAN_MARK_EVICTABLE flag.

EEXIST

The filesystem object indicated by dirfd and pathname has a mark that was updated with the FAN_MARK_IGNORE flag, and the user attempted to update the mark with FAN_MARK_IGNORED_MASK flag.

EEXIST

The filesystem object indicated by dirfd and pathname has a mark that was updated with the FAN_MARK_IGNORE and FAN_MARK_IGNORED_SURV_MODIFY flags, and the user attempted to update the mark only with FAN_MARK_IGNORE flag.

EINVAL

An invalid value was passed in flags or mask, or fanotify_fd was not an fanotify file descriptor.

EINVAL

The fanotify file descriptor was opened with FAN_CLASS_NOTIF or the fanotify group identifies filesystem objects by file handles and mask contains a flag for permission events (FAN_OPEN_PERM or FAN_ACCESS_PERM).

EINVAL

The group was initialized without FAN_REPORT_FID but one or more event types specified in the mask require it.

EINVAL

flags contains FAN_MARK_IGNORE, and either FAN_MARK_MOUNT or FAN_MARK_FILESYSTEM, but does not contain FAN_MARK_IGNORED_SURV_MODIFY.

EISDIR

flags contains FAN_MARK_IGNORE, but does not contain FAN_MARK_IGNORED_SURV_MODIFY, and dirfd and pathname specify a directory.

ENODEV

The filesystem object indicated by dirfd and pathname is not associated with a filesystem that supports fsid (e.g., fuse(4)). tmpfs(5) did not support fsid prior to Linux 5.13. This error can be returned only with an fanotify group that identifies filesystem objects by file handles.

ENOENT

The filesystem object indicated by dirfd and pathname does not exist. This error also occurs when trying to remove a mark from an object which is not marked.

ENOMEM

The necessary memory could not be allocated.

ENOSPC

The number of marks for this user exceeds the limit and the FAN_UNLIMITED_MARKS flag was not specified when the fanotify file descriptor was created with fanotify_init(2). See fanotify(7) for details about this limit.

ENOSYS

This kernel does not implement fanotify_mark(). The fanotify API is available only if the kernel was configured with CONFIG_FANOTIFY.

ENOTDIR

flags contains FAN_MARK_ONLYDIR, and dirfd and pathname do not specify a directory.

ENOTDIR

mask contains FAN_RENAME, and dirfd and pathname do not specify a directory.

ENOTDIR

flags contains FAN_MARK_IGNORE, or the fanotify group was initialized with flag FAN_REPORT_TARGET_FID, and mask contains directory entry modification events (e.g., FAN_CREATE, FAN_DELETE), or directory event flags (e.g., FAN_ONDIR, FAN_EVENT_ON_CHILD), and dirfd and pathname do not specify a directory.

EOPNOTSUPP

The object indicated by pathname is associated with a filesystem that does not support the encoding of file handles. This error can be returned only with an fanotify group that identifies filesystem objects by file handles.

EPERM

The operation is not permitted because the caller lacks a required capability.

EXDEV

The filesystem object indicated by pathname resides within a filesystem subvolume (e.g., btrfs(5)) which uses a different fsid than its root superblock. This error can be returned only with an fanotify group that identifies filesystem objects by file handles.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.37.

## NOTES

### FAN_OPEN_EXEC and FAN_OPEN_EXEC_PERM
When using either FAN_OPEN_EXEC or FAN_OPEN_EXEC_PERM within the mask, events of these types will be returned only when the direct execution of a program occurs. More specifically, this means that events of these types will be generated for files that are opened using execve(2), execveat(2), or uselib(2). Events of these types will not be raised in the situation where an interpreter is passed (or reads) a file for interpretation.

Additionally, if a mark has also been placed on the Linux dynamic linker, a user should also expect to receive an event for it when an ELF object has been successfully opened using execve(2) or execveat(2).

For example, if the following ELF binary were to be invoked and a FAN_OPEN_EXEC mark has been placed on /:

```
$ /bin/echo foo
```

The listening application in this case would receive FAN_OPEN_EXEC events for both the ELF binary and interpreter, respectively:

```
/bin/echo
/lib64/ld-linux-x86-64.so.2
```

## BUGS
The following bugs were present in before Linux 3.16:

•

If flags contains FAN_MARK_FLUSH, dirfd, and pathname must specify a valid filesystem object, even though this object is not used.

•

readdir(2) does not generate a FAN_ACCESS event.

•

If fanotify_mark() is called with FAN_MARK_FLUSH, flags is not checked for invalid values.

## SEE ALSO
fanotify_init(2), fanotify(7)