fanotify

title: fanotify(7)

summary: monitoring filesystem events

text:
# fanotify(7)

## NAME
fanotify - monitoring filesystem events

## DESCRIPTION
The fanotify API provides notification and interception of filesystem events. Use cases include virus scanning and hierarchical storage management. In the original fanotify API, only a limited set of events was supported. In particular, there was no support for create, delete, and move events. The support for those events was added in Linux 5.1. (See inotify(7) for details of an API that did notify those events pre Linux 5.1.)

Additional capabilities compared to the inotify(7) API include the ability to monitor all of the objects in a mounted filesystem, the ability to make access permission decisions, and the possibility to read or modify files before access by other applications.

The following system calls are used with this API: fanotify_init(2), fanotify_mark(2), read(2), write(2), and close(2).

### fanotify_init(), fanotify_mark(), and notification groups
The fanotify_init(2) system call creates and initializes an fanotify notification group and returns a file descriptor referring to it.

An fanotify notification group is a kernel-internal object that holds a list of files, directories, filesystems, and mounts for which events shall be created.

For each entry in an fanotify notification group, two bit masks exist: the mark mask and the ignore mask. The mark mask defines file activities for which an event shall be created. The ignore mask defines activities for which no event shall be generated. Having these two types of masks permits a filesystem, mount, or directory to be marked for receiving events, while at the same time ignoring events for specific objects under a mount or directory.

The fanotify_mark(2) system call adds a file, directory, filesystem, or mount to a notification group and specifies which events shall be reported (or ignored), or removes or modifies such an entry.

A possible usage of the ignore mask is for a file cache. Events of interest for a file cache are modification of a file and closing of the same. Hence, the cached directory or mount is to be marked to receive these events. After receiving the first event informing that a file has been modified, the corresponding cache entry will be invalidated. No further modification events for this file are of interest until the file is closed. Hence, the modify event can be added to the ignore mask. Upon receiving the close event, the modify event can be removed from the ignore mask and the file cache entry can be updated.

The entries in the fanotify notification groups refer to files and directories via their inode number and to mounts via their mount ID. If files or directories are renamed or moved within the same mount, the respective entries survive. If files or directories are deleted or moved to another mount or if filesystems or mounts are unmounted, the corresponding entries are deleted.

### The event queue
As events occur on the filesystem objects monitored by a notification group, the fanotify system generates events that are collected in a queue. These events can then be read (using read(2) or similar) from the fanotify file descriptor returned by fanotify_init(2).

Two types of events are generated: notification events and permission events. Notification events are merely informative and require no action to be taken by the receiving application with one exception: if a valid file descriptor is provided within a generic event, the file descriptor must be closed. Permission events are requests to the receiving application to decide whether permission for a file access shall be granted. For these events, the recipient must write a response which decides whether access is granted or not.

An event is removed from the event queue of the fanotify group when it has been read. Permission events that have been read are kept in an internal list of the fanotify group until either a permission decision has been taken by writing to the fanotify file descriptor or the fanotify file descriptor is closed.

### Reading fanotify events
Calling read(2) for the file descriptor returned by fanotify_init(2) blocks (if the flag FAN_NONBLOCK is not specified in the call to fanotify_init(2)) until either a file event occurs or the call is interrupted by a signal (see signal(7)).

After a successful read(2), the read buffer contains one or more of the following structures:

```
struct fanotify_event_metadata {

    __u32 event_len;

    __u8 vers;

    __u8 reserved;

    __u16 metadata_len;

    __aligned_u64 mask;

    __s32 fd;

    __s32 pid;
};
```

Information records are supplemental pieces of information that may be provided alongside the generic fanotify_event_metadata structure. The flags passed to fanotify_init(2) have influence over the type of information records that may be returned for an event. For example, if a notification group is initialized with FAN_REPORT_FID or FAN_REPORT_DIR_FID, then event listeners should also expect to receive a fanotify_event_info_fid structure alongside the fanotify_event_metadata structure, whereby file handles are used to identify filesystem objects rather than file descriptors. Information records may also be stacked, meaning that using the various FAN_REPORT_* flags in conjunction with one another is supported. In such cases, multiple information records can be returned for an event alongside the generic fanotify_event_metadata structure. For example, if a notification group is initialized with FAN_REPORT_TARGET_FID and FAN_REPORT_PIDFD, then an event listener should expect to receive up to two fanotify_event_info_fid information records and one fanotify_event_info_pidfd information record alongside the generic fanotify_event_metadata structure. Importantly, fanotify provides no guarantee around the ordering of information records when a notification group is initialized with a stacked based configuration. Each information record has a nested structure of type fanotify_event_info_header. It is imperative for event listeners to inspect the info_type field of this structure in order to determine the type of information record that had been received for a given event.

In cases where an fanotify group identifies filesystem objects by file handles, event listeners should also expect to receive one or more of the below information record objects alongside the generic fanotify_event_metadata structure within the read buffer:

```
struct fanotify_event_info_fid {

    struct fanotify_event_info_header hdr;

    __kernel_fsid_t fsid;

    unsigned char file_handle[0];
};
```

In cases where an fanotify group is initialized with FAN_REPORT_PIDFD, event listeners should expect to receive the below information record object alongside the generic fanotify_event_metadata structure within the read buffer:

```
struct fanotify_event_info_pidfd {

        struct fanotify_event_info_header hdr;

        __s32 pidfd;
};
```

In case of a FAN_FS_ERROR event, an additional information record describing the error that occurred is returned alongside the generic fanotify_event_metadata structure within the read buffer. This structure is defined as follows:

```
struct fanotify_event_info_error {

    struct fanotify_event_info_header hdr;

    __s32 error;

    __u32 error_count;
};
```

All information records contain a nested structure of type fanotify_event_info_header. This structure holds meta-information about the information record that may have been returned alongside the generic fanotify_event_metadata structure. This structure is defined as follows:

```
struct fanotify_event_info_header {
	__u8 info_type;
	__u8 pad;
	__u16 len;
};
```

For performance reasons, it is recommended to use a large buffer size (for example, 4096 bytes), so that multiple events can be retrieved by a single read(2).

The return value of read(2) is the number of bytes placed in the buffer, or -1 in case of an error (but see BUGS).

The fields of the fanotify_event_metadata structure are as follows:

event_len

This is the length of the data for the current event and the offset to the next event in the buffer. Unless the group identifies filesystem objects by file handles, the value of event_len is always FAN_EVENT_METADATA_LEN. For a group that identifies filesystem objects by file handles, event_len also includes the variable length file identifier records.

vers

This field holds a version number for the structure. It must be compared to FANOTIFY_METADATA_VERSION to verify that the structures returned at run time match the structures defined at compile time. In case of a mismatch, the application should abandon trying to use the fanotify file descriptor.

reserved

This field is not used.

metadata_len

This is the length of the structure. The field was introduced to facilitate the implementation of optional headers per event type. No such optional headers exist in the current implementation.

mask

This is a bit mask describing the event (see below).

fd

This is an open file descriptor for the object being accessed, or FAN_NOFD if a queue overflow occurred. With an fanotify group that identifies filesystem objects by file handles, applications should expect this value to be set to FAN_NOFD for each event that is received. The file descriptor can be used to access the contents of the monitored file or directory. The reading application is responsible for closing this file descriptor.

When calling fanotify_init(2), the caller may specify (via the event_f_flags argument) various file status flags that are to be set on the open file description that corresponds to this file descriptor. In addition, the (kernel-internal) FMODE_NONOTIFY file status flag is set on the open file description. This flag suppresses fanotify event generation. Hence, when the receiver of the fanotify event accesses the notified file or directory using this file descriptor, no additional events will be created.

pid

If flag FAN_REPORT_TID was set in fanotify_init(2), this is the TID of the thread that caused the event. Otherwise, this the PID of the process that caused the event.

A program listening to fanotify events can compare this PID to the PID returned by getpid(2), to determine whether the event is caused by the listener itself, or is due to a file access by another process.

The bit mask in mask indicates which events have occurred for a single filesystem object. Multiple bits may be set in this mask, if more than one event occurred for the monitored filesystem object. In particular, consecutive events for the same filesystem object and originating from the same process may be merged into a single event, with the exception that two permission events are never merged into one queue entry.

The bits that may appear in mask are as follows:

FAN_ACCESS

A file or a directory (but see BUGS) was accessed (read).

FAN_OPEN

A file or a directory was opened.

FAN_OPEN_EXEC

A file was opened with the intent to be executed. See NOTES in fanotify_mark(2) for additional details.

FAN_ATTRIB

A file or directory metadata was changed.

FAN_CREATE

A child file or directory was created in a watched parent.

FAN_DELETE

A child file or directory was deleted in a watched parent.

FAN_DELETE_SELF

A watched file or directory was deleted.

FAN_FS_ERROR

A filesystem error was detected.

FAN_RENAME

A file or directory has been moved to or from a watched parent directory.

FAN_MOVED_FROM

A file or directory has been moved from a watched parent directory.

FAN_MOVED_TO

A file or directory has been moved to a watched parent directory.

FAN_MOVE_SELF

A watched file or directory was moved.

FAN_MODIFY

A file was modified.

FAN_CLOSE_WRITE

A file that was opened for writing (O_WRONLY or O_RDWR) was closed.

FAN_CLOSE_NOWRITE

A file or directory that was opened read-only (O_RDONLY) was closed.

FAN_Q_OVERFLOW

The event queue exceeded the limit on number of events. This limit can be overridden by specifying the FAN_UNLIMITED_QUEUE flag when calling fanotify_init(2).

FAN_ACCESS_PERM

An application wants to read a file or directory, for example using read(2) or readdir(2). The reader must write a response (as described below) that determines whether the permission to access the filesystem object shall be granted.

FAN_OPEN_PERM

An application wants to open a file or directory. The reader must write a response that determines whether the permission to open the filesystem object shall be granted.

FAN_OPEN_EXEC_PERM

An application wants to open a file for execution. The reader must write a response that determines whether the permission to open the filesystem object for execution shall be granted. See NOTES in fanotify_mark(2) for additional details.

To check for any close event, the following bit mask may be used:

FAN_CLOSE

A file was closed. This is a synonym for:

```
FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE

```

To check for any move event, the following bit mask may be used:

FAN_MOVE

A file or directory was moved. This is a synonym for:

```
FAN_MOVED_FROM | FAN_MOVED_TO

```

The following bits may appear in mask only in conjunction with other event type bits:

FAN_ONDIR

The events described in the mask have occurred on a directory object. Reporting events on directories requires setting this flag in the mark mask. See fanotify_mark(2) for additional details. The FAN_ONDIR flag is reported in an event mask only if the fanotify group identifies filesystem objects by file handles.

Information records that are supplied alongside the generic fanotify_event_metadata structure will always contain a nested structure of type fanotify_event_info_header. The fields of the fanotify_event_info_header are as follows:

info_type

A unique integer value representing the type of information record object received for an event. The value of this field can be set to one of the following: FAN_EVENT_INFO_TYPE_FID, FAN_EVENT_INFO_TYPE_DFID, FAN_EVENT_INFO_TYPE_DFID_NAME, or FAN_EVENT_INFO_TYPE_PIDFD. The value set for this field is dependent on the flags that have been supplied to fanotify_init(2). Refer to the field details of each information record object type below to understand the different cases in which the info_type values can be set.

pad

This field is currently not used by any information record object type and therefore is set to zero.

len

The value of len is set to the size of the information record object, including the fanotify_event_info_header. The total size of all additional information records is not expected to be larger than (event_len - metadata_len).

The fields of the fanotify_event_info_fid structure are as follows:

hdr

This is a structure of type fanotify_event_info_header. For example, when an fanotify file descriptor is created using FAN_REPORT_FID, a single information record is expected to be attached to the event with info_type field value of FAN_EVENT_INFO_TYPE_FID. When an fanotify file descriptor is created using the combination of FAN_REPORT_FID and FAN_REPORT_DIR_FID, there may be two information records attached to the event: one with info_type field value of FAN_EVENT_INFO_TYPE_DFID, identifying a parent directory object, and one with info_type field value of FAN_EVENT_INFO_TYPE_FID, identifying a child object. Note that for the directory entry modification events FAN_CREATE, FAN_DELETE, FAN_MOVE, and FAN_RENAME, an information record identifying the created/deleted/moved child object is reported only if an fanotify group was initialized with the flag FAN_REPORT_TARGET_FID.

fsid

This is a unique identifier of the filesystem containing the object associated with the event. It is a structure of type __kernel_fsid_t and contains the same value as f_fsid when calling statfs(2).

file_handle

This is a variable length structure of type struct file_handle. It is an opaque handle that corresponds to a specified object on a filesystem as returned by name_to_handle_at(2). It can be used to uniquely identify a file on a filesystem and can be passed as an argument to open_by_handle_at(2). If the value of info_type field is FAN_EVENT_INFO_TYPE_DFID_NAME, the file handle is followed by a null terminated string that identifies the created/deleted/moved directory entry name. For other events such as FAN_OPEN, FAN_ATTRIB, FAN_DELETE_SELF, and FAN_MOVE_SELF, if the value of info_type field is FAN_EVENT_INFO_TYPE_FID, the file_handle identifies the object correlated to the event. If the value of info_type field is FAN_EVENT_INFO_TYPE_DFID, the file_handle identifies the directory object correlated to the event or the parent directory of a non-directory object correlated to the event. If the value of info_type field is FAN_EVENT_INFO_TYPE_DFID_NAME, the file_handle identifies the same directory object that would be reported with FAN_EVENT_INFO_TYPE_DFID and the file handle is followed by a null terminated string that identifies the name of a directory entry in that directory, or '.' to identify the directory object itself.

The fields of the fanotify_event_info_pidfd structure are as follows:

hdr

This is a structure of type fanotify_event_info_header. When an fanotify group is initialized using FAN_REPORT_PIDFD, the info_type field value of the fanotify_event_info_header is set to FAN_EVENT_INFO_TYPE_PIDFD.

pidfd

This is a process file descriptor that refers to the process responsible for generating the event. The returned process file descriptor is no different from one which could be obtained manually if pidfd_open(2) were to be called on fanotify_event_metadata.pid. In the instance that an error is encountered during pidfd creation, one of two possible error types represented by a negative integer value may be returned in this pidfd field. In cases where the process responsible for generating the event has terminated prior to the event listener being able to read events from the notification queue, FAN_NOPIDFD is returned. The pidfd creation for an event is only performed at the time the events are read from the notification queue. All other possible pidfd creation failures are represented by FAN_EPIDFD. Once the event listener has dealt with an event and the pidfd is no longer required, the pidfd should be closed via close(2).

The fields of the fanotify_event_info_error structure are as follows:

hdr

This is a structure of type fanotify_event_info_header. The info_type field is set to FAN_EVENT_INFO_TYPE_ERROR.

error

Identifies the type of error that occurred.

error_count

This is a counter of the number of errors suppressed since the last error was read.

The following macros are provided to iterate over a buffer containing fanotify event metadata returned by a read(2) from an fanotify file descriptor:

FAN_EVENT_OK(meta, len)

This macro checks the remaining length len of the buffer meta against the length of the metadata structure and the event_len field of the first metadata structure in the buffer.

FAN_EVENT_NEXT(meta, len)

This macro uses the length indicated in the event_len field of the metadata structure pointed to by meta to calculate the address of the next metadata structure that follows meta. len is the number of bytes of metadata that currently remain in the buffer. The macro returns a pointer to the next metadata structure that follows meta, and reduces len by the number of bytes in the metadata structure that has been skipped over (i.e., it subtracts meta->event_len from len).

In addition, there is:

FAN_EVENT_METADATA_LEN

This macro returns the size (in bytes) of the structure fanotify_event_metadata. This is the minimum size (and currently the only size) of any event metadata.

### Monitoring an fanotify file descriptor for events
When an fanotify event occurs, the fanotify file descriptor indicates as readable when passed to epoll(7), poll(2), or select(2).

### Dealing with permission events
For permission events, the application must write(2) a structure of the following form to the fanotify file descriptor:

```
struct fanotify_response {

    __s32 fd;

    __u32 response;
};
```

The fields of this structure are as follows:

fd

This is the file descriptor from the structure fanotify_event_metadata.

response

This field indicates whether or not the permission is to be granted. Its value must be either FAN_ALLOW to allow the file operation or FAN_DENY to deny the file operation.

If access is denied, the requesting application call will receive an EPERM error. Additionally, if the notification group has been created with the FAN_ENABLE_AUDIT flag, then the FAN_AUDIT flag can be set in the response field. In that case, the audit subsystem will log information about the access decision to the audit logs.

### Monitoring filesystems for errors
A single FAN_FS_ERROR event is stored per filesystem at once. Extra error messages are suppressed and accounted for in the error_count field of the existing FAN_FS_ERROR event record, but details about the errors are lost.

Errors reported by FAN_FS_ERROR are generic errno values, but not all kinds of error types are reported by all filesystems.

Errors not directly related to a file (i.e. super block corruption) are reported with an invalid file_handle. For these errors, the file_handle will have the field handle_type set to FILEID_INVALID, and the handle buffer size set to 0.

### Closing the fanotify file descriptor
When all file descriptors referring to the fanotify notification group are closed, the fanotify group is released and its resources are freed for reuse by the kernel. Upon close(2), outstanding permission events will be set to allowed.

### /proc interfaces
The file /proc/pid/fdinfo/fd contains information about fanotify marks for file descriptor fd of process pid. See proc(5) for details.

Since Linux 5.13, the following interfaces can be used to control the amount of kernel resources consumed by fanotify:

/proc/sys/fs/fanotify/max_queued_events

The value in this file is used when an application calls fanotify_init(2) to set an upper limit on the number of events that can be queued to the corresponding fanotify group. Events in excess of this limit are dropped, but an FAN_Q_OVERFLOW event is always generated. Prior to Linux kernel 5.13, the hardcoded limit was 16384 events.

/proc/sys/fs/fanotify/max_user_group

This specifies an upper limit on the number of fanotify groups that can be created per real user ID. Prior to Linux kernel 5.13, the hardcoded limit was 128 groups per user.

/proc/sys/fs/fanotify/max_user_marks

This specifies an upper limit on the number of fanotify marks that can be created per real user ID. Prior to Linux kernel 5.13, the hardcoded limit was 8192 marks per group (not per user).

## ERRORS
In addition to the usual errors for read(2), the following errors can occur when reading from the fanotify file descriptor:

EINVAL

The buffer is too small to hold the event.

EMFILE

The per-process limit on the number of open files has been reached. See the description of RLIMIT_NOFILE in getrlimit(2).

ENFILE

The system-wide limit on the total number of open files has been reached. See /proc/sys/fs/file-max in proc(5).

ETXTBSY

This error is returned by read(2) if O_RDWR or O_WRONLY was specified in the event_f_flags argument when calling fanotify_init(2) and an event occurred for a monitored file that is currently being executed.

In addition to the usual errors for write(2), the following errors can occur when writing to the fanotify file descriptor:

EINVAL

Fanotify access permissions are not enabled in the kernel configuration or the value of response in the response structure is not valid.

ENOENT

The file descriptor fd in the response structure is not valid. This may occur when a response for the permission event has already been written.

## STANDARDS
Linux.

## HISTORY
The fanotify API was introduced in Linux 2.6.36 and enabled in Linux 2.6.37. fdinfo support was added in Linux 3.8.

## NOTES
The fanotify API is available only if the kernel was built with the CONFIG_FANOTIFY configuration option enabled. In addition, fanotify permission handling is available only if the CONFIG_FANOTIFY_ACCESS_PERMISSIONS configuration option is enabled.

### Limitations and caveats
Fanotify reports only events that a user-space program triggers through the filesystem API. As a result, it does not catch remote events that occur on network filesystems.

The fanotify API does not report file accesses and modifications that may occur because of mmap(2), msync(2), and munmap(2).

Events for directories are created only if the directory itself is opened, read, and closed. Adding, removing, or changing children of a marked directory does not create events for the monitored directory itself.

Fanotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional marks must be created. The FAN_CREATE event can be used for detecting when a subdirectory has been created under a marked directory. An additional mark must then be set on the newly created subdirectory. This approach is racy, because it can lose events that occurred inside the newly created subdirectory, before a mark is added on that subdirectory. Monitoring mounts offers the capability to monitor a whole directory tree in a race-free manner. Monitoring filesystems offers the capability to monitor changes made from any mount of a filesystem instance in a race-free manner.

The event queue can overflow. In this case, events are lost.

## BUGS
Before Linux 3.19, fallocate(2) did not generate fanotify events. Since Linux 3.19, calls to fallocate(2) generate FAN_MODIFY events.

As of Linux 3.17, the following bugs exist:

•

On Linux, a filesystem object may be accessible through multiple paths, for example, a part of a filesystem may be remounted using the --bind option of mount(8). A listener that marked a mount will be notified only of events that were triggered for a filesystem object using the same mount. Any other event will pass unnoticed.

•

When an event is generated, no check is made to see whether the user ID of the receiving process has authorization to read or write the file before passing a file descriptor for that file. This poses a security risk, when the CAP_SYS_ADMIN capability is set for programs executed by unprivileged users.

•

If a call to read(2) processes multiple events from the fanotify queue and an error occurs, the return value will be the total length of the events successfully copied to the user-space buffer before the error occurred. The return value will not be -1, and errno will not be set. Thus, the reading application has no way to detect the error.

## EXAMPLES
The two example programs below demonstrate the usage of the fanotify API.

### Example program: fanotify_example.c
The first program is an example of fanotify being used with its event object information passed in the form of a file descriptor. The program marks the mount passed as a command-line argument and waits for events of type FAN_OPEN_PERM and FAN_CLOSE_WRITE. When a permission event occurs, a FAN_ALLOW response is given.

The following shell session shows an example of running this program. This session involved editing the file /home/user/temp/notes. Before the file was opened, a FAN_OPEN_PERM event occurred. After the file was closed, a FAN_CLOSE_WRITE event occurred. Execution of the program ends when the user presses the ENTER key.

```
# ./fanotify_example /home
Press enter key to terminate.
Listening for events.
FAN_OPEN_PERM: File /home/user/temp/notes
FAN_CLOSE_WRITE: File /home/user/temp/notes
Listening for events stopped.
```

### Program source: fanotify_example.c

```
#define _GNU_SOURCE     /* Needed to get O_LARGEFILE definition */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/fanotify.h>
#include <unistd.h>
/* Read all available fanotify events from the file descriptor 'fd'. */
static void
handle_events(int fd)
{

    const struct fanotify_event_metadata *metadata;

    struct fanotify_event_metadata buf[200];

    ssize_t len;

    char path[PATH_MAX];

    ssize_t path_len;

    char procfd_path[PATH_MAX];

    struct fanotify_response response;

    /* Loop while events can be read from fanotify file descriptor. */

    for (;;) {

        /* Read some events. */

        len = read(fd, buf, sizeof(buf));

        if (len == -1 && errno != EAGAIN) {

            perror("read");

            exit(EXIT_FAILURE);

        }

        /* Check if end of available data reached. */

        if (len <= 0)

            break;

        /* Point to the first event in the buffer. */

        metadata = buf;

        /* Loop over all events in the buffer. */

        while (FAN_EVENT_OK(metadata, len)) {

            /* Check that run-time and compile-time structures match. */

            if (metadata->vers != FANOTIFY_METADATA_VERSION) {

                fprintf(stderr,

                        "Mismatch of fanotify metadata version.\n");

                exit(EXIT_FAILURE);

            }

            /* metadata->fd contains either FAN_NOFD, indicating a

               queue overflow, or a file descriptor (a nonnegative

               integer). Here, we simply ignore queue overflow. */

            if (metadata->fd >= 0) {

                /* Handle open permission event. */

                if (metadata->mask & FAN_OPEN_PERM) {

                    printf("FAN_OPEN_PERM: ");

                    /* Allow file to be opened. */

                    response.fd = metadata->fd;

                    response.response = FAN_ALLOW;

                    write(fd, &response, sizeof(response));

                }

                /* Handle closing of writable file event. */

                if (metadata->mask & FAN_CLOSE_WRITE)

                    printf("FAN_CLOSE_WRITE: ");

                /* Retrieve and print pathname of the accessed file. */

                snprintf(procfd_path, sizeof(procfd_path),

                         "/proc/self/fd/%d", metadata->fd);

                path_len = readlink(procfd_path, path,

                                    sizeof(path) - 1);

                if (path_len == -1) {

                    perror("readlink");

                    exit(EXIT_FAILURE);

                }

                path[path_len] = '\0';

                printf("File %s\n", path);

                /* Close the file descriptor of the event. */

                close(metadata->fd);

            }

            /* Advance to next event. */

            metadata = FAN_EVENT_NEXT(metadata, len);

        }

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

    char buf;

    int fd, poll_num;

    nfds_t nfds;

    struct pollfd fds[2];

    /* Check mount point is supplied. */

    if (argc != 2) {

        fprintf(stderr, "Usage: %s MOUNT\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    printf("Press enter key to terminate.\n");

    /* Create the file descriptor for accessing the fanotify API. */

    fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,

                       O_RDONLY | O_LARGEFILE);

    if (fd == -1) {

        perror("fanotify_init");

        exit(EXIT_FAILURE);

    }

    /* Mark the mount for:

       - permission events before opening files

       - notification events after closing a write-enabled

         file descriptor. */

    if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,

                      FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,

                      argv[1]) == -1) {

        perror("fanotify_mark");

        exit(EXIT_FAILURE);

    }

    /* Prepare for polling. */

    nfds = 2;

    fds[0].fd = STDIN_FILENO;       /* Console input */

    fds[0].events = POLLIN;

    fds[1].fd = fd;                 /* Fanotify input */

    fds[1].events = POLLIN;

    /* This is the loop to wait for incoming events. */

    printf("Listening for events.\n");

    while (1) {

        poll_num = poll(fds, nfds, -1);

        if (poll_num == -1) {

            if (errno == EINTR)     /* Interrupted by a signal */

                continue;           /* Restart poll() */

            perror("poll");         /* Unexpected error */

            exit(EXIT_FAILURE);

        }

        if (poll_num > 0) {

            if (fds[0].revents & POLLIN) {

                /* Console input is available: empty stdin and quit. */

                while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')

                    continue;

                break;

            }

            if (fds[1].revents & POLLIN) {

                /* Fanotify events are available. */

                handle_events(fd);

            }

        }

    }

    printf("Listening for events stopped.\n");

    exit(EXIT_SUCCESS);
}
```

### Example program: fanotify_fid.c
The second program is an example of fanotify being used with a group that identifies objects by file handles. The program marks the filesystem object that is passed as a command-line argument and waits until an event of type FAN_CREATE has occurred. The event mask indicates which type of filesystem object—either a file or a directory—was created. Once all events have been read from the buffer and processed accordingly, the program simply terminates.

The following shell sessions show two different invocations of this program, with different actions performed on a watched object.

The first session shows a mark being placed on /home/user. This is followed by the creation of a regular file, /home/user/testfile.txt. This results in a FAN_CREATE event being generated and reported against the file's parent watched directory object and with the created file name. Program execution ends once all events captured within the buffer have been processed.

```
# ./fanotify_fid /home/user
Listening for events.
FAN_CREATE (file created):

        Directory /home/user has been modified.

        Entry 'testfile.txt' is not a subdirectory.
All events processed successfully. Program exiting.
$ touch /home/user/testfile.txt              # In another terminal
```

The second session shows a mark being placed on /home/user. This is followed by the creation of a directory, /home/user/testdir. This specific action results in a FAN_CREATE event being generated and is reported with the FAN_ONDIR flag set and with the created directory name.

```
# ./fanotify_fid /home/user
Listening for events.
FAN_CREATE | FAN_ONDIR (subdirectory created):

        Directory /home/user has been modified.

        Entry 'testdir' is a subdirectory.
All events processed successfully. Program exiting.
$ mkdir -p /home/user/testdir          # In another terminal
```

### Program source: fanotify_fid.c

```
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fanotify.h>
#include <unistd.h>
#define BUF_SIZE 256
int
main(int argc, char *argv[])
{

    int fd, ret, event_fd, mount_fd;

    ssize_t len, path_len;

    char path[PATH_MAX];

    char procfd_path[PATH_MAX];

    char events_buf[BUF_SIZE];

    struct file_handle *file_handle;

    struct fanotify_event_metadata *metadata;

    struct fanotify_event_info_fid *fid;

    const char *file_name;

    struct stat sb;

    if (argc != 2) {

        fprintf(stderr, "Invalid number of command line arguments.\n");

        exit(EXIT_FAILURE);

    }

    mount_fd = open(argv[1], O_DIRECTORY | O_RDONLY);

    if (mount_fd == -1) {

        perror(argv[1]);

        exit(EXIT_FAILURE);

    }

    /* Create an fanotify file descriptor with FAN_REPORT_DFID_NAME as

       a flag so that program can receive fid events with directory

       entry name. */

    fd = fanotify_init(FAN_CLASS_NOTIF | FAN_REPORT_DFID_NAME, 0);

    if (fd == -1) {

        perror("fanotify_init");

        exit(EXIT_FAILURE);

    }

    /* Place a mark on the filesystem object supplied in argv[1]. */

    ret = fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_ONLYDIR,

                        FAN_CREATE | FAN_ONDIR,

                        AT_FDCWD, argv[1]);

    if (ret == -1) {

        perror("fanotify_mark");

        exit(EXIT_FAILURE);

    }

    printf("Listening for events.\n");

    /* Read events from the event queue into a buffer. */

    len = read(fd, events_buf, sizeof(events_buf));

    if (len == -1 && errno != EAGAIN) {

        perror("read");

        exit(EXIT_FAILURE);

    }

    /* Process all events within the buffer. */

    for (metadata = (struct fanotify_event_metadata *) events_buf;

            FAN_EVENT_OK(metadata, len);

            metadata = FAN_EVENT_NEXT(metadata, len)) {

        fid = (struct fanotify_event_info_fid *) (metadata + 1);

        file_handle = (struct file_handle *) fid->handle;

        /* Ensure that the event info is of the correct type. */

        if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_FID ||

            fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID) {

            file_name = NULL;

        } else if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID_NAME) {

            file_name = file_handle->f_handle +

                        file_handle->handle_bytes;

        } else {

            fprintf(stderr, "Received unexpected event info type.\n");

            exit(EXIT_FAILURE);

        }

        if (metadata->mask == FAN_CREATE)

            printf("FAN_CREATE (file created):\n");

        if (metadata->mask == (FAN_CREATE | FAN_ONDIR))

            printf("FAN_CREATE | FAN_ONDIR (subdirectory created):\n");
	/* metadata->fd is set to FAN_NOFD when the group identifies
	   objects by file handles.  To obtain a file descriptor for
	   the file object corresponding to an event you can use the
	   struct file_handle that's provided within the
	   fanotify_event_info_fid in conjunction with the
	   open_by_handle_at(2) system call.  A check for ESTALE is
	   done to accommodate for the situation where the file handle
	   for the object was deleted prior to this system call. */

        event_fd = open_by_handle_at(mount_fd, file_handle, O_RDONLY);

        if (event_fd == -1) {

            if (errno == ESTALE) {

                printf("File handle is no longer valid. "

                        "File has been deleted\n");

                continue;

            } else {

                perror("open_by_handle_at");

                exit(EXIT_FAILURE);

            }

        }

        snprintf(procfd_path, sizeof(procfd_path), "/proc/self/fd/%d",

                event_fd);

        /* Retrieve and print the path of the modified dentry. */

        path_len = readlink(procfd_path, path, sizeof(path) - 1);

        if (path_len == -1) {

            perror("readlink");

            exit(EXIT_FAILURE);

        }

        path[path_len] = '\0';

        printf("\tDirectory '%s' has been modified.\n", path);

        if (file_name) {

            ret = fstatat(event_fd, file_name, &sb, 0);

            if (ret == -1) {

                if (errno != ENOENT) {

                    perror("fstatat");

                    exit(EXIT_FAILURE);

                }

                printf("\tEntry '%s' does not exist.\n", file_name);

            } else if ((sb.st_mode & S_IFMT) == S_IFDIR) {

                printf("\tEntry '%s' is a subdirectory.\n", file_name);

            } else {

                printf("\tEntry '%s' is not a subdirectory.\n",

                        file_name);

            }

        }

        /* Close associated file descriptor for this event. */

        close(event_fd);

    }

    printf("All events processed successfully. Program exiting.\n");

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
fanotify_init(2), fanotify_mark(2), inotify(7)


package: man-pages

title: feature_test_macros(7)

summary: feature test macros

text:
# feature_test_macros(7)

## NAME
feature_test_macros - feature test macros

## DESCRIPTION
Feature test macros allow the programmer to control the definitions that are exposed by system header files when a program is compiled.

NOTE: In order to be effective, a feature test macro must be defined before including any header files. This can be done either in the compilation command (cc -DMACRO=value) or by defining the macro within the source code before including any headers. The requirement that the macro must be defined before including any header file exists because header files may freely include one another. Thus, for example, in the following lines, defining the _GNU_SOURCE macro may have no effect because the header <abc.h> itself includes <xyz.h> (POSIX explicitly allows this):

```
#include <abc.h>
#define _GNU_SOURCE
#include <xyz.h>
```

Some feature test macros are useful for creating portable applications, by preventing nonstandard definitions from being exposed. Other macros can be used to expose nonstandard definitions that are not exposed by default.

The precise effects of each of the feature test macros described below can be ascertained by inspecting the <features.h> header file. Note: applications do not need to directly include <features.h>; indeed, doing so is actively discouraged. See NOTES.

### Specification of feature test macro requirements in manual pages
When a function requires that a feature test macro is defined, the manual page SYNOPSIS typically includes a note of the following form (this example from the acct(2) manual page):

\#include <unistd.h> int acct(const char *filename);

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

acct(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

The || means that in order to obtain the declaration of acct(2) from <unistd.h>, either of the following macro definitions must be made before including any header files:

```
#define _BSD_SOURCE
#define _XOPEN_SOURCE        /* or any value < 500 */
```

Alternatively, equivalent definitions can be included in the compilation command:

```
cc -D_BSD_SOURCE
cc -D_XOPEN_SOURCE           # Or any value < 500
```

Note that, as described below, some feature test macros are defined by default, so that it may not always be necessary to explicitly specify the feature test macro(s) shown in the SYNOPSIS.

In a few cases, manual pages use a shorthand for expressing the feature test macro requirements (this example from readahead(2)):

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

```
ssize_t readahead(int fd, off_t *offset, size_t count);
```

This format is employed when the feature test macros ensure that the proper function declarations are visible, and the macros are not defined by default.

### Feature test macros understood by glibc
The paragraphs below explain how feature test macros are handled in glibc 2.x, x > 0.

First, though, a summary of a few details for the impatient:

•

The macros that you most likely need to use in modern source code are _POSIX_C_SOURCE (for definitions from various versions of POSIX.1), _XOPEN_SOURCE (for definitions from various versions of SUS), _GNU_SOURCE (for GNU and/or Linux specific stuff), and _DEFAULT_SOURCE (to get definitions that would normally be provided by default).

•

Certain macros are defined with default values. Thus, although one or more macros may be indicated as being required in the SYNOPSIS of a man page, it may not be necessary to define them explicitly. Full details of the defaults are given later in this man page.

•

Defining _XOPEN_SOURCE with a value of 600 or greater produces the same effects as defining _POSIX_C_SOURCE with a value of 200112L or greater. Where one sees

```
_POSIX_C_SOURCE >= 200112L

```

in the feature test macro requirements in the SYNOPSIS of a man page, it is implicit that the following has the same effect:

```
_XOPEN_SOURCE >= 600

```

•

Defining _XOPEN_SOURCE with a value of 700 or greater produces the same effects as defining _POSIX_C_SOURCE with a value of 200809L or greater. Where one sees

```
_POSIX_C_SOURCE >= 200809L

```

in the feature test macro requirements in the SYNOPSIS of a man page, it is implicit that the following has the same effect:

```
_XOPEN_SOURCE >= 700

```

glibc understands the following feature test macros:

__STRICT_ANSI__

ISO Standard C. This macro is implicitly defined by gcc(1) when invoked with, for example, the -std=c99 or -ansi flag.

_POSIX_C_SOURCE

Defining this macro causes header files to expose definitions as follows:

•

The value 1 exposes definitions conforming to POSIX.1-1990 and ISO C (1990).

•

The value 2 or greater additionally exposes definitions for POSIX.2-1992.

•

The value 199309L or greater additionally exposes definitions for POSIX.1b (real-time extensions).

•

The value 199506L or greater additionally exposes definitions for POSIX.1c (threads).

•

(Since glibc 2.3.3) The value 200112L or greater additionally exposes definitions corresponding to the POSIX.1-2001 base specification (excluding the XSI extension). This value also causes C95 (since glibc 2.12) and C99 (since glibc 2.10) features to be exposed (in other words, the equivalent of defining _ISOC99_SOURCE).

•

(Since glibc 2.10) The value 200809L or greater additionally exposes definitions corresponding to the POSIX.1-2008 base specification (excluding the XSI extension).

_POSIX_SOURCE

Defining this obsolete macro with any value is equivalent to defining _POSIX_C_SOURCE with the value 1.

Since this macro is obsolete, its usage is generally not documented when discussing feature test macro requirements in the man pages.

_XOPEN_SOURCE

Defining this macro causes header files to expose definitions as follows:

•

Defining with any value exposes definitions conforming to POSIX.1, POSIX.2, and XPG4.

•

The value 500 or greater additionally exposes definitions for SUSv2 (UNIX 98).

•

(Since glibc 2.2) The value 600 or greater additionally exposes definitions for SUSv3 (UNIX 03; i.e., the POSIX.1-2001 base specification plus the XSI extension) and C99 definitions.

•

(Since glibc 2.10) The value 700 or greater additionally exposes definitions for SUSv4 (i.e., the POSIX.1-2008 base specification plus the XSI extension).

If __STRICT_ANSI__ is not defined, or _XOPEN_SOURCE is defined with a value greater than or equal to 500 and neither _POSIX_SOURCE nor _POSIX_C_SOURCE is explicitly defined, then the following macros are implicitly defined:

•

_POSIX_SOURCE is defined with the value 1.

•

_POSIX_C_SOURCE is defined, according to the value of _XOPEN_SOURCE:

_XOPEN_SOURCE < 500

_POSIX_C_SOURCE is defined with the value 2.

500 <= _XOPEN_SOURCE < 600

_POSIX_C_SOURCE is defined with the value 199506L.

600 <= _XOPEN_SOURCE < 700

_POSIX_C_SOURCE is defined with the value 200112L.

700 <= _XOPEN_SOURCE (since glibc 2.10)

_POSIX_C_SOURCE is defined with the value 200809L.

In addition, defining _XOPEN_SOURCE with a value of 500 or greater produces the same effects as defining _XOPEN_SOURCE_EXTENDED.

_XOPEN_SOURCE_EXTENDED

If this macro is defined, and _XOPEN_SOURCE is defined, then expose definitions corresponding to the XPG4v2 (SUSv1) UNIX extensions (UNIX 95). Defining _XOPEN_SOURCE with a value of 500 or more also produces the same effect as defining _XOPEN_SOURCE_EXTENDED. Use of _XOPEN_SOURCE_EXTENDED in new source code should be avoided.

Since defining _XOPEN_SOURCE with a value of 500 or more has the same effect as defining _XOPEN_SOURCE_EXTENDED, the latter (obsolete) feature test macro is generally not described in the SYNOPSIS in man pages.

_ISOC99_SOURCE (since glibc 2.1.3)

Exposes declarations consistent with the ISO C99 standard.

Earlier glibc 2.1.x versions recognized an equivalent macro named _ISOC9X_SOURCE (because the C99 standard had not then been finalized). Although the use of this macro is obsolete, glibc continues to recognize it for backward compatibility.

Defining _ISOC99_SOURCE also exposes ISO C (1990) Amendment 1 ("C95") definitions. (The primary change in C95 was support for international character sets.)

Invoking the C compiler with the option -std=c99 produces the same effects as defining this macro.

_ISOC11_SOURCE (since glibc 2.16)

Exposes declarations consistent with the ISO C11 standard. Defining this macro also enables C99 and C95 features (like _ISOC99_SOURCE).

Invoking the C compiler with the option -std=c11 produces the same effects as defining this macro.

_LARGEFILE64_SOURCE

Expose definitions for the alternative API specified by the LFS (Large File Summit) as a "transitional extension" to the Single UNIX Specification. (See http://opengroup.org/platform/lfs.html.) The alternative API consists of a set of new objects (i.e., functions and types) whose names are suffixed with "64" (e.g., off64_t versus off_t, lseek64() versus lseek(), etc.). New programs should not employ this macro; instead _FILE_OFFSET_BITS=64 should be employed.

_LARGEFILE_SOURCE

This macro was historically used to expose certain functions (specifically fseeko(3) and ftello(3)) that address limitations of earlier APIs (fseek(3) and ftell(3)) that use long for file offsets. This macro is implicitly defined if _XOPEN_SOURCE is defined with a value greater than or equal to 500. New programs should not employ this macro; defining _XOPEN_SOURCE as just described or defining _FILE_OFFSET_BITS with the value 64 is the preferred mechanism to achieve the same result.

_FILE_OFFSET_BITS

Defining this macro with the value 64 automatically converts references to 32-bit functions and data types related to file I/O and filesystem operations into references to their 64-bit counterparts. This is useful for performing I/O on large files (> 2 Gigabytes) on 32-bit systems. It is also useful when calling functions like copy_file_range(2) that were added more recently and that come only in 64-bit flavors. (Defining this macro permits correctly written programs to use large files with only a recompilation being required.)

64-bit systems naturally permit file sizes greater than 2 Gigabytes, and on those systems this macro has no effect.

_TIME_BITS

Defining this macro with the value 64 changes the width of time_t(3type) to 64-bit which allows handling of timestamps beyond 2038. It is closely related to _FILE_OFFSET_BITS and depending on implementation, may require it set. This macro is available as of glibc 2.34.

_BSD_SOURCE (deprecated since glibc 2.20)

Defining this macro with any value causes header files to expose BSD-derived definitions.

In glibc versions up to and including 2.18, defining this macro also causes BSD definitions to be preferred in some situations where standards conflict, unless one or more of _SVID_SOURCE, _POSIX_SOURCE, _POSIX_C_SOURCE, _XOPEN_SOURCE, _XOPEN_SOURCE_EXTENDED, or _GNU_SOURCE is defined, in which case BSD definitions are disfavored. Since glibc 2.19, _BSD_SOURCE no longer causes BSD definitions to be preferred in case of conflicts.

Since glibc 2.20, this macro is deprecated. It now has the same effect as defining _DEFAULT_SOURCE, but generates a compile-time warning (unless _DEFAULT_SOURCE is also defined). Use _DEFAULT_SOURCE instead. To allow code that requires _BSD_SOURCE in glibc 2.19 and earlier and _DEFAULT_SOURCE in glibc 2.20 and later to compile without warnings, define both _BSD_SOURCE and _DEFAULT_SOURCE.

_SVID_SOURCE (deprecated since glibc 2.20)

Defining this macro with any value causes header files to expose System V-derived definitions. (SVID == System V Interface Definition; see standards(7).)

Since glibc 2.20, this macro is deprecated in the same fashion as _BSD_SOURCE.

_DEFAULT_SOURCE (since glibc 2.19)

This macro can be defined to ensure that the "default" definitions are provided even when the defaults would otherwise be disabled, as happens when individual macros are explicitly defined, or the compiler is invoked in one of its "standard" modes (e.g., cc -std=c99). Defining _DEFAULT_SOURCE without defining other individual macros or invoking the compiler in one of its "standard" modes has no effect.

The "default" definitions comprise those required by POSIX.1-2008 and ISO C99, as well as various definitions originally derived from BSD and System V. On glibc 2.19 and earlier, these defaults were approximately equivalent to explicitly defining the following:

```
cc -D_BSD_SOURCE -D_SVID_SOURCE -D_POSIX_C_SOURCE=200809

```

_ATFILE_SOURCE (since glibc 2.4)

Defining this macro with any value causes header files to expose declarations of a range of functions with the suffix "at"; see openat(2). Since glibc 2.10, this macro is also implicitly defined if _POSIX_C_SOURCE is defined with a value greater than or equal to 200809L.

_GNU_SOURCE

Defining this macro (with any value) implicitly defines _ATFILE_SOURCE, _LARGEFILE64_SOURCE, _ISOC99_SOURCE, _XOPEN_SOURCE_EXTENDED, _POSIX_SOURCE, _POSIX_C_SOURCE with the value 200809L (200112L before glibc 2.10; 199506L before glibc 2.5; 199309L before glibc 2.1) and _XOPEN_SOURCE with the value 700 (600 before glibc 2.10; 500 before glibc 2.2). In addition, various GNU-specific extensions are also exposed.

Since glibc 2.19, defining _GNU_SOURCE also has the effect of implicitly defining _DEFAULT_SOURCE. Before glibc 2.20, defining _GNU_SOURCE also had the effect of implicitly defining _BSD_SOURCE and _SVID_SOURCE.

_REENTRANT

Historically, on various C libraries it was necessary to define this macro in all multithreaded code. (Some C libraries may still require this.) In glibc, this macro also exposed definitions of certain reentrant functions.

However, glibc has been thread-safe by default for many years; since glibc 2.3, the only effect of defining _REENTRANT has been to enable one or two of the same declarations that are also enabled by defining _POSIX_C_SOURCE with a value of 199606L or greater.

_REENTRANT is now obsolete. In glibc 2.25 and later, defining _REENTRANT is equivalent to defining _POSIX_C_SOURCE with the value 199606L. If a higher POSIX conformance level is selected by any other means (such as _POSIX_C_SOURCE itself, _XOPEN_SOURCE, _DEFAULT_SOURCE, or _GNU_SOURCE), then defining _REENTRANT has no effect.

This macro is automatically defined if one compiles with cc -pthread.

_THREAD_SAFE

Synonym for the (deprecated) _REENTRANT, provided for compatibility with some other implementations.

_FORTIFY_SOURCE (since glibc 2.3.4)

Defining this macro causes some lightweight checks to be performed to detect some buffer overflow errors when employing various string and memory manipulation functions (for example, memcpy(3), memset(3), stpcpy(3), strcpy(3), strncpy(3), strcat(3), strncat(3), sprintf(3), snprintf(3), vsprintf(3), vsnprintf(3), gets(3), and wide character variants thereof). For some functions, argument consistency is checked; for example, a check is made that open(2) has been supplied with a mode argument when the specified flags include O_CREAT. Not all problems are detected, just some common cases.

If _FORTIFY_SOURCE is set to 1, with compiler optimization level 1 (gcc -O1) and above, checks that shouldn't change the behavior of conforming programs are performed. With _FORTIFY_SOURCE set to 2, some more checking is added, but some conforming programs might fail.

Some of the checks can be performed at compile time (via macros logic implemented in header files), and result in compiler warnings; other checks take place at run time, and result in a run-time error if the check fails.

With _FORTIFY_SOURCE set to 3, additional checking is added to intercept some function calls used with an argument of variable size where the compiler can deduce an upper bound for its value. For example, a program where malloc(3)'s size argument is variable can now be fortified.

Use of this macro requires compiler support, available since gcc 4.0 and clang 2.6. Use of _FORTIFY_SOURCE set to 3 requires gcc 12.0 or later, or clang 9.0 or later, in conjunction with glibc 2.33 or later.

### Default definitions, implicit definitions, and combining definitions
If no feature test macros are explicitly defined, then the following feature test macros are defined by default: _BSD_SOURCE (in glibc 2.19 and earlier), _SVID_SOURCE (in glibc 2.19 and earlier), _DEFAULT_SOURCE (since glibc 2.19), _POSIX_SOURCE, and _POSIX_C_SOURCE=200809L (200112L before glibc 2.10; 199506L before glibc 2.4; 199309L before glibc 2.1).

If any of __STRICT_ANSI__, _ISOC99_SOURCE, _ISOC11_SOURCE (since glibc 2.18), _POSIX_SOURCE, _POSIX_C_SOURCE, _XOPEN_SOURCE, _XOPEN_SOURCE_EXTENDED (in glibc 2.11 and earlier), _BSD_SOURCE (in glibc 2.19 and earlier), or _SVID_SOURCE (in glibc 2.19 and earlier) is explicitly defined, then _BSD_SOURCE, _SVID_SOURCE, and _DEFAULT_SOURCE are not defined by default.

If _POSIX_SOURCE and _POSIX_C_SOURCE are not explicitly defined, and either __STRICT_ANSI__ is not defined or _XOPEN_SOURCE is defined with a value of 500 or more, then

•

_POSIX_SOURCE is defined with the value 1; and

•

_POSIX_C_SOURCE is defined with one of the following values:

•

2, if _XOPEN_SOURCE is defined with a value less than 500;

•

199506L, if _XOPEN_SOURCE is defined with a value greater than or equal to 500 and less than 600; or

•

(since glibc 2.4) 200112L, if _XOPEN_SOURCE is defined with a value greater than or equal to 600 and less than 700.

•

(Since glibc 2.10) 200809L, if _XOPEN_SOURCE is defined with a value greater than or equal to 700.

•

Older versions of glibc do not know about the values 200112L and 200809L for _POSIX_C_SOURCE, and the setting of this macro will depend on the glibc version.

•

If _XOPEN_SOURCE is undefined, then the setting of _POSIX_C_SOURCE depends on the glibc version: 199506L, before glibc 2.4; 200112L, since glibc 2.4 to glibc 2.9; and 200809L, since glibc 2.10.

Multiple macros can be defined; the results are additive.

## STANDARDS
POSIX.1 specifies _POSIX_C_SOURCE, _POSIX_SOURCE, and _XOPEN_SOURCE.

_FILE_OFFSET_BITS is not specified by any standard, but is employed on some other implementations.

_BSD_SOURCE, _SVID_SOURCE, _DEFAULT_SOURCE, _ATFILE_SOURCE, _GNU_SOURCE, _FORTIFY_SOURCE, _REENTRANT, and _THREAD_SAFE are specific to glibc.

## HISTORY
_XOPEN_SOURCE_EXTENDED was specified by XPG4v2 (aka SUSv1), but is not present in SUSv2 and later.

## NOTES
<features.h> is a Linux/glibc-specific header file. Other systems have an analogous file, but typically with a different name. This header file is automatically included by other header files as required: it is not necessary to explicitly include it in order to employ feature test macros.

According to which of the above feature test macros are defined, <features.h> internally defines various other macros that are checked by other glibc header files. These macros have names prefixed by two underscores (e.g., __USE_MISC). Programs should never define these macros directly: instead, the appropriate feature test macro(s) from the list above should be employed.

## EXAMPLES
The program below can be used to explore how the various feature test macros are set depending on the glibc version and what feature test macros are explicitly set. The following shell session, on a system with glibc 2.10, shows some examples of what we would see:

```
$ cc ftm.c
$ ./a.out
_POSIX_SOURCE defined
_POSIX_C_SOURCE defined: 200809L
_BSD_SOURCE defined
_SVID_SOURCE defined
_ATFILE_SOURCE defined
$ cc -D_XOPEN_SOURCE=500 ftm.c
$ ./a.out
_POSIX_SOURCE defined
_POSIX_C_SOURCE defined: 199506L
_XOPEN_SOURCE defined: 500
$ cc -D_GNU_SOURCE ftm.c
$ ./a.out
_POSIX_SOURCE defined
_POSIX_C_SOURCE defined: 200809L
_ISOC99_SOURCE defined
_XOPEN_SOURCE defined: 700
_XOPEN_SOURCE_EXTENDED defined
_LARGEFILE64_SOURCE defined
_BSD_SOURCE defined
_SVID_SOURCE defined
_ATFILE_SOURCE defined
_GNU_SOURCE defined
```

### Program source

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

    printf("_POSIX_SOURCE defined\n");
#endif
#ifdef _POSIX_C_SOURCE

    printf("_POSIX_C_SOURCE defined: %jdL\n",

            (intmax_t) _POSIX_C_SOURCE);
#endif
#ifdef _ISOC99_SOURCE

    printf("_ISOC99_SOURCE defined\n");
#endif
#ifdef _ISOC11_SOURCE

    printf("_ISOC11_SOURCE defined\n");
#endif
#ifdef _XOPEN_SOURCE

    printf("_XOPEN_SOURCE defined: %d\n", _XOPEN_SOURCE);
#endif
#ifdef _XOPEN_SOURCE_EXTENDED

    printf("_XOPEN_SOURCE_EXTENDED defined\n");
#endif
#ifdef _LARGEFILE64_SOURCE

    printf("_LARGEFILE64_SOURCE defined\n");
#endif
#ifdef _FILE_OFFSET_BITS

    printf("_FILE_OFFSET_BITS defined: %d\n", _FILE_OFFSET_BITS);
#endif
#ifdef _TIME_BITS

    printf("_TIME_BITS defined: %d\n", _TIME_BITS);
#endif
#ifdef _BSD_SOURCE

    printf("_BSD_SOURCE defined\n");
#endif
#ifdef _SVID_SOURCE

    printf("_SVID_SOURCE defined\n");
#endif
#ifdef _DEFAULT_SOURCE

    printf("_DEFAULT_SOURCE defined\n");
#endif
#ifdef _ATFILE_SOURCE

    printf("_ATFILE_SOURCE defined\n");
#endif
#ifdef _GNU_SOURCE

    printf("_GNU_SOURCE defined\n");
#endif
#ifdef _REENTRANT

    printf("_REENTRANT defined\n");
#endif
#ifdef _THREAD_SAFE

    printf("_THREAD_SAFE defined\n");
#endif
#ifdef _FORTIFY_SOURCE

    printf("_FORTIFY_SOURCE defined\n");
#endif

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
libc(7), standards(7), system_data_types(7)

The section "Feature Test Macros" under info libc.

/usr/include/features.h

branch: sisyphus


fifo

title: fifo(7)

text:
# fifo(7)

## NAME
fifo - first-in first-out special file, named pipe

## DESCRIPTION
A FIFO special file (a named pipe) is similar to a pipe, except that it is accessed as part of the filesystem. It can be opened by multiple processes for reading or writing. When processes are exchanging data via the FIFO, the kernel passes all data internally without writing it to the filesystem. Thus, the FIFO special file has no contents on the filesystem; the filesystem entry merely serves as a reference point so that processes can access the pipe using a name in the filesystem.

The kernel maintains exactly one pipe object for each FIFO special file that is opened by at least one process. The FIFO must be opened on both ends (reading and writing) before data can be passed. Normally, opening the FIFO blocks until the other end is opened also.

A process can open a FIFO in nonblocking mode. In this case, opening for read-only succeeds even if no one has opened on the write side yet and opening for write-only fails with ENXIO (no such device or address) unless the other end has already been opened.

Under Linux, opening a FIFO for read and write will succeed both in blocking and nonblocking mode. POSIX leaves this behavior undefined. This can be used to open a FIFO for writing while there are no readers available. A process that uses both ends of the connection in order to communicate with itself should be very careful to avoid deadlocks.

## NOTES
For details of the semantics of I/O on FIFOs, see pipe(7).

When a process tries to write to a FIFO that is not opened for read on the other side, the process is sent a SIGPIPE signal.

FIFO special files can be created by mkfifo(3), and are indicated by ls -l with the file type 'p'.

## SEE ALSO
mkfifo(1), open(2), pipe(2), sigaction(2), signal(2), socketpair(2), mkfifo(3), pipe(7)


futex

title: futex(7)

summary: fast user-space locking

text:
# futex(7)

## NAME
futex - fast user-space locking

## SYNOPSIS

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

## DESCRIPTION
The Linux kernel provides futexes ("Fast user-space mutexes") as a building block for fast user-space locking and semaphores. Futexes are very basic and lend themselves well for building higher-level locking abstractions such as mutexes, condition variables, read-write locks, barriers, and semaphores.

Most programmers will in fact not be using futexes directly but will instead rely on system libraries built on them, such as the Native POSIX Thread Library (NPTL) (see pthreads(7)).

A futex is identified by a piece of memory which can be shared between processes or threads. In these different processes, the futex need not have identical addresses. In its bare form, a futex has semaphore semantics; it is a counter that can be incremented and decremented atomically; processes can wait for the value to become positive.

Futex operation occurs entirely in user space for the noncontended case. The kernel is involved only to arbitrate the contended case. As any sane design will strive for noncontention, futexes are also optimized for this situation.

In its bare form, a futex is an aligned integer which is touched only by atomic assembler instructions. This integer is four bytes long on all platforms. Processes can share this integer using mmap(2), via shared memory segments, or because they share memory space, in which case the application is commonly called multithreaded.

### Semantics
Any futex operation starts in user space, but it may be necessary to communicate with the kernel using the futex(2) system call.

To "up" a futex, execute the proper assembler instructions that will cause the host CPU to atomically increment the integer. Afterward, check if it has in fact changed from 0 to 1, in which case there were no waiters and the operation is done. This is the noncontended case which is fast and should be common.

In the contended case, the atomic increment changed the counter from -1 (or some other negative number). If this is detected, there are waiters. User space should now set the counter to 1 and instruct the kernel to wake up any waiters using the FUTEX_WAKE operation.

Waiting on a futex, to "down" it, is the reverse operation. Atomically decrement the counter and check if it changed to 0, in which case the operation is done and the futex was uncontended. In all other circumstances, the process should set the counter to -1 and request that the kernel wait for another process to up the futex. This is done using the FUTEX_WAIT operation.

The futex(2) system call can optionally be passed a timeout specifying how long the kernel should wait for the futex to be upped. In this case, semantics are more complex and the programmer is referred to futex(2) for more details. The same holds for asynchronous futex waiting.

## VERSIONS
Initial futex support was merged in Linux 2.5.7 but with different semantics from those described above. Current semantics are available from Linux 2.5.40 onward.

## NOTES
To reiterate, bare futexes are not intended as an easy-to-use abstraction for end users. Implementors are expected to be assembly literate and to have read the sources of the futex user-space library referenced below.

This man page illustrates the most common use of the futex(2) primitives; it is by no means the only one.

## SEE ALSO
clone(2), futex(2), get_robust_list(2), set_robust_list(2), set_tid_address(2), pthreads(7)

Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux (proceedings of the Ottawa Linux Symposium 2002), futex example library, futex-*.tar.bz2 https://mirrors.kernel.org/pub/linux/kernel/people/rusty/.


glob

title: glob(7)

summary: globbing pathnames

text:
# glob(7)

## NAME
glob - globbing pathnames

## DESCRIPTION
Long ago, in UNIX V6, there was a program /etc/glob that would expand wildcard patterns. Soon afterward this became a shell built-in.

These days there is also a library routine glob(3) that will perform this function for a user program.

The rules are as follows (POSIX.2, 3.13).

### Wildcard matching
A string is a wildcard pattern if it contains one of the characters '?', '*', or '['. Globbing is the operation that expands a wildcard pattern into the list of pathnames matching the pattern. Matching is defined by:

A '?' (not between brackets) matches any single character.

A '*' (not between brackets) matches any string, including the empty string.

Character classes

An expression "[...]" where the first character after the leading '[' is not an '!' matches a single character, namely any of the characters enclosed by the brackets. The string enclosed by the brackets cannot be empty; therefore ']' can be allowed between the brackets, provided that it is the first character. (Thus, "[][!]" matches the three characters '[', ']', and '!'.)

Ranges

There is one special convention: two characters separated by '-' denote a range. (Thus, "[A-Fa-f0-9]" is equivalent to "[ABCDEFabcdef0123456789]".) One may include '-' in its literal meaning by making it the first or last character between the brackets. (Thus, "[]-]" matches just the two characters ']' and '-', and "[--0]" matches the three characters '-', '.', and '0', since '/' cannot be matched.)

Complementation

An expression "[!...]" matches a single character, namely any character that is not matched by the expression obtained by removing the first '!' from it. (Thus, "[!]a-]" matches any single character except ']', 'a', and '-'.)

One can remove the special meaning of '?', '*', and '[' by preceding them by a backslash, or, in case this is part of a shell command line, enclosing them in quotes. Between brackets these characters stand for themselves. Thus, "[[?*\]" matches the four characters '[', '?', '*', and '\'.

### Pathnames
Globbing is applied on each of the components of a pathname separately. A '/' in a pathname cannot be matched by a '?' or '*' wildcard, or by a range like "[.-0]". A range containing an explicit '/' character is syntactically incorrect. (POSIX requires that syntactically incorrect patterns are left unchanged.)

If a filename starts with a '.', this character must be matched explicitly. (Thus, rm * will not remove .profile, and tar c * will not archive all your files; tar c . is better.)

### Empty lists
The nice and simple rule given above: "expand a wildcard pattern into the list of matching pathnames" was the original UNIX definition. It allowed one to have patterns that expand into an empty list, as in

```
    xv -wait 0 *.gif *.jpg
```

where perhaps no *.gif files are present (and this is not an error). However, POSIX requires that a wildcard pattern is left unchanged when it is syntactically incorrect, or the list of matching pathnames is empty. With bash one can force the classical behavior using this command:

```
shopt -s nullglob
```

(Similar problems occur elsewhere. For example, where old scripts have

```
rm `find . -name "*~"`
```

new scripts require

```
rm -f nosuchfile `find . -name "*~"`
```

to avoid error messages from rm called with an empty argument list.)

## NOTES

### Regular expressions
Note that wildcard patterns are not regular expressions, although they are a bit similar. First of all, they match filenames, rather than text, and secondly, the conventions are not the same: for example, in a regular expression '*' means zero or more copies of the preceding thing.

Now that regular expressions have bracket expressions where the negation is indicated by a '^', POSIX has declared the effect of a wildcard pattern "[^...]" to be undefined.

### Character classes and internationalization
Of course ranges were originally meant to be ASCII ranges, so that "[ -%]" stands for "[ !"#$%]" and "[a-z]" stands for "any lowercase letter". Some UNIX implementations generalized this so that a range X-Y stands for the set of characters with code between the codes for X and for Y. However, this requires the user to know the character coding in use on the local system, and moreover, is not convenient if the collating sequence for the local alphabet differs from the ordering of the character codes. Therefore, POSIX extended the bracket notation greatly, both for wildcard patterns and for regular expressions. In the above we saw three types of items that can occur in a bracket expression: namely (i) the negation, (ii) explicit single characters, and (iii) ranges. POSIX specifies ranges in an internationally more useful way and adds three more types:

(iii) Ranges X-Y comprise all characters that fall between X and Y (inclusive) in the current collating sequence as defined by the LC_COLLATE category in the current locale.

(iv) Named character classes, like

```
[:alnum:]  [:alpha:]  [:blank:]  [:cntrl:]
[:digit:]  [:graph:]  [:lower:]  [:print:]
[:punct:]  [:space:]  [:upper:]  [:xdigit:]
```

so that one can say "[[:lower:]]" instead of "[a-z]", and have things work in Denmark, too, where there are three letters past 'z' in the alphabet. These character classes are defined by the LC_CTYPE category in the current locale.

(v) Collating symbols, like "[.ch.]" or "[.a-acute.]", where the string between "[." and ".]" is a collating element defined for the current locale. Note that this may be a multicharacter element.

(vi) Equivalence class expressions, like "[=a=]", where the string between "[=" and "=]" is any collating element from its equivalence class, as defined for the current locale. For example, "[[=a=]]" might be equivalent to "[aáàäâ]", that is, to "[a[.a-acute.][.a-grave.][.a-umlaut.][.a-circumflex.]]".

## SEE ALSO
sh(1), fnmatch(3), glob(3), locale(7), regex(7)


hier

title: hier(7)

summary: description of the filesystem hierarchy

text:
# hier(7)

## NAME
hier - description of the filesystem hierarchy

## DESCRIPTION
A typical Linux system has, among others, the following directories:

/

This is the root directory. This is where the whole tree starts.

/bin

This directory contains executable programs which are needed in single user mode and to bring the system up or repair it.

/boot

Contains static files for the boot loader. This directory holds only the files which are needed during the boot process. The map installer and configuration files should go to /sbin and /etc. The operating system kernel (initrd for example) must be located in either / or /boot.

/dev

Special or device files, which refer to physical devices. See mknod(1).

/etc

Contains configuration files which are local to the machine. Some larger software packages, like X11, can have their own subdirectories below /etc. Site-wide configuration files may be placed here or in /usr/etc. Nevertheless, programs should always look for these files in /etc and you may have links for these files to /usr/etc.

/etc/opt

Host-specific configuration files for add-on applications installed in /opt.

/etc/sgml

This directory contains the configuration files for SGML (optional).

/etc/skel

When a new user account is created, files from this directory are usually copied into the user's home directory.

/etc/X11

Configuration files for the X11 window system (optional).

/etc/xml

This directory contains the configuration files for XML (optional).

/home

On machines with home directories for users, these are usually beneath this directory, directly or not. The structure of this directory depends on local administration decisions (optional).

/lib

This directory should hold those shared libraries that are necessary to boot the system and to run the commands in the root filesystem.

/lib<qual>

These directories are variants of /lib on system which support more than one binary format requiring separate libraries (optional).

/lib/modules

Loadable kernel modules (optional).

/lost+found

This directory contains items lost in the filesystem. These items are usually chunks of files mangled as a consequence of a faulty disk or a system crash.

/media

This directory contains mount points for removable media such as CD and DVD disks or USB sticks. On systems where more than one device exists for mounting a certain type of media, mount directories can be created by appending a digit to the name of those available above starting with '0', but the unqualified name must also exist.

/media/floppy[1-9]

Floppy drive (optional).

/media/cdrom[1-9]

CD-ROM drive (optional).

/media/cdrecorder[1-9]

CD writer (optional).

/media/zip[1-9]

Zip drive (optional).

/media/usb[1-9]

USB drive (optional).

/mnt

This directory is a mount point for a temporarily mounted filesystem. In some distributions, /mnt contains subdirectories intended to be used as mount points for several temporary filesystems.

/opt

This directory should contain add-on packages that contain static files.

/proc

This is a mount point for the proc filesystem, which provides information about running processes and the kernel. This pseudo-filesystem is described in more detail in proc(5).

/root

This directory is usually the home directory for the root user (optional).

/run

This directory contains information which describes the system since it was booted. Once this purpose was served by /var/run and programs may continue to use it.

/sbin

Like /bin, this directory holds commands needed to boot the system, but which are usually not executed by normal users.

/srv

This directory contains site-specific data that is served by this system.

/sys

This is a mount point for the sysfs filesystem, which provides information about the kernel like /proc, but better structured, following the formalism of kobject infrastructure.

/tmp

This directory contains temporary files which may be deleted with no notice, such as by a regular job or at system boot up.

/usr

This directory is usually mounted from a separate partition. It should hold only shareable, read-only data, so that it can be mounted by various machines running Linux.

/usr/X11R6

The X-Window system, version 11 release 6 (present in FHS 2.3, removed in FHS 3.0).

/usr/X11R6/bin

Binaries which belong to the X-Window system; often, there is a symbolic link from the more traditional /usr/bin/X11 to here.

/usr/X11R6/lib

Data files associated with the X-Window system.

/usr/X11R6/lib/X11

These contain miscellaneous files needed to run X; Often, there is a symbolic link from /usr/lib/X11 to this directory.

/usr/X11R6/include/X11

Contains include files needed for compiling programs using the X11 window system. Often, there is a symbolic link from /usr/include/X11 to this directory.

/usr/bin

This is the primary directory for executable programs. Most programs executed by normal users which are not needed for booting or for repairing the system and which are not installed locally should be placed in this directory.

/usr/bin/mh

Commands for the MH mail handling system (optional).

/usr/bin/X11

This is the traditional place to look for X11 executables; on Linux, it usually is a symbolic link to /usr/X11R6/bin.

/usr/dict

Replaced by /usr/share/dict.

/usr/doc

Replaced by /usr/share/doc.

/usr/etc

Site-wide configuration files to be shared between several machines may be stored in this directory. However, commands should always reference those files using the /etc directory. Links from files in /etc should point to the appropriate files in /usr/etc.

/usr/games

Binaries for games and educational programs (optional).

/usr/include

Include files for the C compiler.

/usr/include/bsd

BSD compatibility include files (optional).

/usr/include/X11

Include files for the C compiler and the X-Window system. This is usually a symbolic link to /usr/X11R6/include/X11.

/usr/include/asm

Include files which declare some assembler functions. This used to be a symbolic link to /usr/src/linux/include/asm.

/usr/include/linux

This contains information which may change from system release to system release and used to be a symbolic link to /usr/src/linux/include/linux to get at operating-system-specific information.

(Note that one should have include files there that work correctly with the current libc and in user space. However, Linux kernel source is not designed to be used with user programs and does not know anything about the libc you are using. It is very likely that things will break if you let /usr/include/asm and /usr/include/linux point at a random kernel tree. Debian systems don't do this and use headers from a known good kernel version, provided in the libc*-dev package.)

/usr/include/g++

Include files to use with the GNU C++ compiler.

/usr/lib

Object libraries, including dynamic libraries, plus some executables which usually are not invoked directly. More complicated programs may have whole subdirectories there.

/usr/libexec

Directory contains binaries for internal use only and they are not meant to be executed directly by users shell or scripts.

/usr/lib<qual>

These directories are variants of /usr/lib on system which support more than one binary format requiring separate libraries, except that the symbolic link /usr/libqual/X11 is not required (optional).

/usr/lib/X11

The usual place for data files associated with X programs, and configuration files for the X system itself. On Linux, it usually is a symbolic link to /usr/X11R6/lib/X11.

/usr/lib/gcc-lib

contains executables and include files for the GNU C compiler, gcc(1).

/usr/lib/groff

Files for the GNU groff document formatting system.

/usr/lib/uucp

Files for uucp(1).

/usr/local

This is where programs which are local to the site typically go.

/usr/local/bin

Binaries for programs local to the site.

/usr/local/doc

Local documentation.

/usr/local/etc

Configuration files associated with locally installed programs.

/usr/local/games

Binaries for locally installed games.

/usr/local/lib

Files associated with locally installed programs.

/usr/local/lib<qual>

These directories are variants of /usr/local/lib on system which support more than one binary format requiring separate libraries (optional).

/usr/local/include

Header files for the local C compiler.

/usr/local/info

Info pages associated with locally installed programs.

/usr/local/man

Man pages associated with locally installed programs.

/usr/local/sbin

Locally installed programs for system administration.

/usr/local/share

Local application data that can be shared among different architectures of the same OS.

/usr/local/src

Source code for locally installed software.

/usr/man

Replaced by /usr/share/man.

/usr/sbin

This directory contains program binaries for system administration which are not essential for the boot process, for mounting /usr, or for system repair.

/usr/share

This directory contains subdirectories with specific application data, that can be shared among different architectures of the same OS. Often one finds stuff here that used to live in /usr/doc or /usr/lib or /usr/man.

/usr/share/color

Contains color management information, like International Color Consortium (ICC) Color profiles (optional).

/usr/share/dict

Contains the word lists used by spell checkers (optional).

/usr/share/dict/words

List of English words (optional).

/usr/share/doc

Documentation about installed programs (optional).

/usr/share/games

Static data files for games in /usr/games (optional).

/usr/share/info

Info pages go here (optional).

/usr/share/locale

Locale information goes here (optional).

/usr/share/man

Manual pages go here in subdirectories according to the man page sections.

/usr/share/man/locale/man[1-9]

These directories contain manual pages for the specific locale in source code form. Systems which use a unique language and code set for all manual pages may omit the <locale> substring.

/usr/share/misc

Miscellaneous data that can be shared among different architectures of the same OS.

/usr/share/nls

The message catalogs for native language support go here (optional).

/usr/share/ppd

Postscript Printer Definition (PPD) files (optional).

/usr/share/sgml

Files for SGML (optional).

/usr/share/sgml/docbook

DocBook DTD (optional).

/usr/share/sgml/tei

TEI DTD (optional).

/usr/share/sgml/html

HTML DTD (optional).

/usr/share/sgml/mathml

MathML DTD (optional).

/usr/share/terminfo

The database for terminfo (optional).

/usr/share/tmac

Troff macros that are not distributed with groff (optional).

/usr/share/xml

Files for XML (optional).

/usr/share/xml/docbook

DocBook DTD (optional).

/usr/share/xml/xhtml

XHTML DTD (optional).

/usr/share/xml/mathml

MathML DTD (optional).

/usr/share/zoneinfo

Files for timezone information (optional).

/usr/src

Source files for different parts of the system, included with some packages for reference purposes. Don't work here with your own projects, as files below /usr should be read-only except when installing software (optional).

/usr/src/linux

This was the traditional place for the kernel source. Some distributions put here the source for the default kernel they ship. You should probably use another directory when building your own kernel.

/usr/tmp

Obsolete. This should be a link to /var/tmp. This link is present only for compatibility reasons and shouldn't be used.

/var

This directory contains files which may change in size, such as spool and log files.

/var/account

Process accounting logs (optional).

/var/adm

This directory is superseded by /var/log and should be a symbolic link to /var/log.

/var/backups

Reserved for historical reasons.

/var/cache

Data cached for programs.

/var/cache/fonts

Locally generated fonts (optional).

/var/cache/man

Locally formatted man pages (optional).

/var/cache/www

WWW proxy or cache data (optional).

/var/cache/<package>

Package specific cache data (optional).

/var/catman/cat[1-9] or /var/cache/man/cat[1-9]

These directories contain preformatted manual pages according to their man page section. (The use of preformatted manual pages is deprecated.)

/var/crash

System crash dumps (optional).

/var/cron

Reserved for historical reasons.

/var/games

Variable game data (optional).

/var/lib

Variable state information for programs.

/var/lib/color

Variable files containing color management information (optional).

/var/lib/hwclock

State directory for hwclock (optional).

/var/lib/misc

Miscellaneous state data.

/var/lib/xdm

X display manager variable data (optional).

/var/lib/<editor>

Editor backup files and state (optional).

/var/lib/<name>

These directories must be used for all distribution packaging support.

/var/lib/<package>

State data for packages and subsystems (optional).

/var/lib/<pkgtool>

Packaging support files (optional).

/var/local

Variable data for /usr/local.

/var/lock

Lock files are placed in this directory. The naming convention for device lock files is LCK..<device> where <device> is the device's name in the filesystem. The format used is that of HDU UUCP lock files, that is, lock files contain a PID as a 10-byte ASCII decimal number, followed by a newline character.

/var/log

Miscellaneous log files.

/var/opt

Variable data for /opt.

/var/mail

Users' mailboxes. Replaces /var/spool/mail.

/var/msgs

Reserved for historical reasons.

/var/preserve

Reserved for historical reasons.

/var/run

Run-time variable files, like files holding process identifiers (PIDs) and logged user information (utmp). Files in this directory are usually cleared when the system boots.

/var/spool

Spooled (or queued) files for various programs.

/var/spool/at

Spooled jobs for at(1).

/var/spool/cron

Spooled jobs for cron(8).

/var/spool/lpd

Spooled files for printing (optional).

/var/spool/lpd/printer

Spools for a specific printer (optional).

/var/spool/mail

Replaced by /var/mail.

/var/spool/mqueue

Queued outgoing mail (optional).

/var/spool/news

Spool directory for news (optional).

/var/spool/rwho

Spooled files for rwhod(8) (optional).

/var/spool/smail

Spooled files for the smail(1) mail delivery program.

/var/spool/uucp

Spooled files for uucp(1) (optional).

/var/tmp

Like /tmp, this directory holds temporary files stored for an unspecified duration.

/var/yp

Database files for NIS, formerly known as the Sun Yellow Pages (YP).

## STANDARDS
The Filesystem Hierarchy Standard (FHS), Version 3.0, published March 19, 2015

## BUGS
This list is not exhaustive; different distributions and systems may be configured differently.

## SEE ALSO
find(1), ln(1), proc(5), file-hierarchy(7), mount(8)

The Filesystem Hierarchy Standard


hostname

title: hostname(7)

summary: hostname resolution description

text:
# hostname(7)

## NAME
hostname - hostname resolution description

## DESCRIPTION
Hostnames are domains, where a domain is a hierarchical, dot-separated list of subdomains; for example, the machine "monet", in the "example" subdomain of the "com" domain would be represented as "monet.example.com".

Each element of the hostname must be from 1 to 63 characters long and the entire hostname, including the dots, can be at most 253 characters long. Valid characters for hostnames are ASCII(7) letters from a to z, the digits from 0 to 9, and the hyphen (-). A hostname may not start with a hyphen.

Hostnames are often used with network client and server programs, which must generally translate the name to an address for use. (This task is generally performed by either getaddrinfo(3) or the obsolete gethostbyname(3).)

Hostnames are resolved by the NSS framework in glibc according to the hosts configuration in nsswitch.conf. The DNS-based name resolver (in the dns NSS service module) resolves them in the following fashion.

If the name consists of a single component, that is, contains no dot, and if the environment variable HOSTALIASES is set to the name of a file, that file is searched for any string matching the input hostname. The file should consist of lines made up of two white-space separated strings, the first of which is the hostname alias, and the second of which is the complete hostname to be substituted for that alias. If a case-insensitive match is found between the hostname to be resolved and the first field of a line in the file, the substituted name is looked up with no further processing.

If the input name ends with a trailing dot, the trailing dot is removed, and the remaining name is looked up with no further processing.

If the input name does not end with a trailing dot, it is looked up by searching through a list of domains until a match is found. The default search list includes first the local domain, then its parent domains with at least 2 name components (longest first). For example, in the domain cs.example.com, the name lithium.cchem will be checked first as lithium.cchem.cs.example and then as lithium.cchem.example.com. lithium.cchem.com will not be tried, as there is only one component remaining from the local domain. The search path can be changed from the default by a system-wide configuration file (see resolver(5)).

## SEE ALSO
getaddrinfo(3), gethostbyname(3), nsswitch.conf(5), resolver(5), mailaddr(7), named(8)

IETF RFC 1123

IETF RFC 1178


icmp

title: icmp(7)

summary: Linux IPv4 ICMP kernel module.

text:
# icmp(7)

## NAME
icmp - Linux IPv4 ICMP kernel module.

## DESCRIPTION
This kernel protocol module implements the Internet Control Message Protocol defined in RFC 792. It is used to signal error conditions and for diagnosis. The user doesn't interact directly with this module; instead it communicates with the other protocols in the kernel and these pass the ICMP errors to the application layers. The kernel ICMP module also answers ICMP requests.

A user protocol may receive ICMP packets for all local sockets by opening a raw socket with the protocol IPPROTO_ICMP. See raw(7) for more information. The types of ICMP packets passed to the socket can be filtered using the ICMP_FILTER socket option. ICMP packets are always processed by the kernel too, even when passed to a user socket.

Linux limits the rate of ICMP error packets to each destination. ICMP_REDIRECT and ICMP_DEST_UNREACH are also limited by the destination route of the incoming packets.

### /proc interfaces
ICMP supports a set of /proc interfaces to configure some global IP parameters. The parameters can be accessed by reading or writing files in the directory /proc/sys/net/ipv4/. Most of these parameters are rate limitations for specific ICMP types. Linux 2.2 uses a token bucket filter to limit ICMPs. The value is the timeout in jiffies until the token bucket filter is cleared after a burst. A jiffy is a system dependent unit, usually 10ms on i386 and about 1ms on alpha and ia64.

icmp_destunreach_rate (Linux 2.2 to Linux 2.4.9)

Maximum rate to send ICMP Destination Unreachable packets. This limits the rate at which packets are sent to any individual route or destination. The limit does not affect sending of ICMP_FRAG_NEEDED packets needed for path MTU discovery.

icmp_echo_ignore_all (since Linux 2.2)

If this value is nonzero, Linux will ignore all ICMP_ECHO requests.

icmp_echo_ignore_broadcasts (since Linux 2.2)

If this value is nonzero, Linux will ignore all ICMP_ECHO packets sent to broadcast addresses.

icmp_echoreply_rate (Linux 2.2 to Linux 2.4.9)

Maximum rate for sending ICMP_ECHOREPLY packets in response to ICMP_ECHOREQUEST packets.

icmp_errors_use_inbound_ifaddr (Boolean; default: disabled; since Linux 2.6.12)

If disabled, ICMP error messages are sent with the primary address of the exiting interface.

If enabled, the message will be sent with the primary address of the interface that received the packet that caused the ICMP error. This is the behavior that many network administrators will expect from a router. And it can make debugging complicated network layouts much easier.

Note that if no primary address exists for the interface selected, then the primary address of the first non-loopback interface that has one will be used regardless of this setting.

icmp_ignore_bogus_error_responses (Boolean; default: disabled; since Linux 2.2)

Some routers violate RFC1122 by sending bogus responses to broadcast frames. Such violations are normally logged via a kernel warning. If this parameter is enabled, the kernel will not give such warnings, which will avoid log file clutter.

icmp_paramprob_rate (Linux 2.2 to Linux 2.4.9)

Maximum rate for sending ICMP_PARAMETERPROB packets. These packets are sent when a packet arrives with an invalid IP header.

icmp_ratelimit (integer; default: 1000; since Linux 2.4.10)

Limit the maximum rates for sending ICMP packets whose type matches icmp_ratemask (see below) to specific targets. 0 to disable any limiting, otherwise the minimum space between responses in milliseconds.

icmp_ratemask (integer; default: see below; since Linux 2.4.10)

Mask made of ICMP types for which rates are being limited.

Significant bits: IHGFEDCBA9876543210

Default mask: 0000001100000011000 (0x1818)

Bit definitions (see the Linux kernel source file include/linux/icmp.h):

0 Echo Reply

3 Destination Unreachable *

4 Source Quench *

5 Redirect

8 Echo Request

B Time Exceeded *

C Parameter Problem *

D Timestamp Request

E Timestamp Reply

F Info Request

G Info Reply

H Address Mask Request

I Address Mask Reply

The bits marked with an asterisk are rate limited by default (see the default mask above).

icmp_timeexceed_rate (Linux 2.2 to Linux 2.4.9)

Maximum rate for sending ICMP_TIME_EXCEEDED packets. These packets are sent to prevent loops when a packet has crossed too many hops.

ping_group_range (two integers; default: see below; since Linux 2.6.39)

Range of the group IDs (minimum and maximum group IDs, inclusive) that are allowed to create ICMP Echo sockets. The default is "1 0", which means no group is allowed to create ICMP Echo sockets.

## VERSIONS
Support for the ICMP_ADDRESS request was removed in Linux 2.2.

Support for ICMP_SOURCE_QUENCH was removed in Linux 2.2.

## NOTES
As many other implementations don't support IPPROTO_ICMP raw sockets, this feature should not be relied on in portable programs.

ICMP_REDIRECT packets are not sent when Linux is not acting as a router. They are also accepted only from the old gateway defined in the routing table and the redirect routes are expired after some time.

The 64-bit timestamp returned by ICMP_TIMESTAMP is in milliseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

Linux ICMP internally uses a raw socket to send ICMPs. This raw socket may appear in netstat(8) output with a zero inode.

## SEE ALSO
ip(7), rdisc(8)

RFC 792 for a description of the ICMP protocol.