msgctl

title: msgctl(2)

summary: System V message control operations

text:
# msgctl(2)

## NAME
msgctl - System V message control operations

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

## SYNOPSIS

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

```
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
```

## DESCRIPTION
msgctl() performs the control operation specified by cmd on the System V message queue with identifier msqid.

The msqid_ds data structure is defined in <sys/msg.h> as follows:

```
struct msqid_ds {

    struct ipc_perm msg_perm;   /* Ownership and permissions */

    time_t          msg_stime;  /* Time of last msgsnd(2) */

    time_t          msg_rtime;  /* Time of last msgrcv(2) */

    time_t          msg_ctime;  /* Time of creation or last

                                   modification by msgctl() */

    unsigned long   msg_cbytes; /* # of bytes in queue */

    msgqnum_t       msg_qnum;   /* # number of messages in queue */

    msglen_t        msg_qbytes; /* Maximum # of bytes in queue */

    pid_t           msg_lspid;  /* PID of last msgsnd(2) */

    pid_t           msg_lrpid;  /* PID of last msgrcv(2) */
};
```

The fields of the msqid_ds structure are as follows:

msg_perm

This is an ipc_perm structure (see below) that specifies the access permissions on the message queue.

msg_stime

Time of the last msgsnd(2) system call.

msg_rtime

Time of the last msgrcv(2) system call.

msg_ctime

Time of creation of queue or time of last msgctl() IPC_SET operation.

msg_cbytes

Number of bytes in all messages currently on the message queue. This is a nonstandard Linux extension that is not specified in POSIX.

msg_qnum

Number of messages currently on the message queue.

msg_qbytes

Maximum number of bytes of message text allowed on the message queue.

msg_lspid

ID of the process that performed the last msgsnd(2) system call.

msg_lrpid

ID of the process that performed the last msgrcv(2) system call.

The ipc_perm structure is defined as follows (the highlighted fields are settable using IPC_SET):

```
struct ipc_perm {

    key_t          __key;       /* Key supplied to msgget(2) */

    uid_t          uid;         /* Effective UID of owner */

    gid_t          gid;         /* Effective GID of owner */

    uid_t          cuid;        /* Effective UID of creator */

    gid_t          cgid;        /* Effective GID of creator */

    unsigned short mode;        /* Permissions */

    unsigned short __seq;       /* Sequence number */
};
```

The least significant 9 bits of the mode field of the ipc_perm structure define the access permissions for the message queue. The permission bits are as follows:

0400

Read by user

0200

Write by user

0040

Read by group

0020

Write by group

0004

Read by others

0002

Write by others

Bits 0100, 0010, and 0001 (the execute bits) are unused by the system.

Valid values for cmd are:

IPC_STAT

Copy information from the kernel data structure associated with msqid into the msqid_ds structure pointed to by buf. The caller must have read permission on the message queue.

IPC_SET

Write the values of some members of the msqid_ds structure pointed to by buf to the kernel data structure associated with this message queue, updating also its msg_ctime member.

The following members of the structure are updated: msg_qbytes, msg_perm.uid, msg_perm.gid, and (the least significant 9 bits of) msg_perm.mode.

The effective UID of the calling process must match the owner (msg_perm.uid) or creator (msg_perm.cuid) of the message queue, or the caller must be privileged. Appropriate privilege (Linux: the CAP_SYS_RESOURCE capability) is required to raise the msg_qbytes value beyond the system parameter MSGMNB.

IPC_RMID

Immediately remove the message queue, awakening all waiting reader and writer processes (with an error return and errno set to EIDRM). The calling process must have appropriate privileges or its effective user ID must be either that of the creator or owner of the message queue. The third argument to msgctl() is ignored in this case.

IPC_INFO (Linux-specific)

Return information about system-wide message queue limits and parameters in the structure pointed to by buf. This structure is of type msginfo (thus, a cast is required), defined in <sys/msg.h> if the _GNU_SOURCE feature test macro is defined:

```
struct msginfo {

    int msgpool; /* Size in kibibytes of buffer pool

                    used to hold message data;

                    unused within kernel */

    int msgmap;  /* Maximum number of entries in message

                    map; unused within kernel */

    int msgmax;  /* Maximum number of bytes that can be

                    written in a single message */

    int msgmnb;  /* Maximum number of bytes that can be

                    written to queue; used to initialize

                    msg_qbytes during queue creation

                    (msgget(2)) */

    int msgmni;  /* Maximum number of message queues */

    int msgssz;  /* Message segment size;

                    unused within kernel */

    int msgtql;  /* Maximum number of messages on all queues

                    in system; unused within kernel */

    unsigned short msgseg;

                 /* Maximum number of segments;

                    unused within kernel */
};

```

The msgmni, msgmax, and msgmnb settings can be changed via /proc files of the same name; see proc(5) for details.

MSG_INFO (Linux-specific)

Return a msginfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by message queues: the msgpool field returns the number of message queues that currently exist on the system; the msgmap field returns the total number of messages in all queues on the system; and the msgtql field returns the total number of bytes in all messages in all queues on the system.

MSG_STAT (Linux-specific)

Return a msqid_ds structure as for IPC_STAT. However, the msqid argument is not a queue identifier, but instead an index into the kernel's internal array that maintains information about all message queues on the system.

MSG_STAT_ANY (Linux-specific, since Linux 4.17)

Return a msqid_ds structure as for MSG_STAT. However, msg_perm.mode is not checked for read access for msqid meaning that any user can employ this operation (just as any user may read /proc/sysvipc/msg to obtain the same information).

## RETURN VALUE
On success, IPC_STAT, IPC_SET, and IPC_RMID return 0. A successful IPC_INFO or MSG_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all message queues. (This information can be used with repeated MSG_STAT or MSG_STAT_ANY operations to obtain information about all queues on the system.) A successful MSG_STAT or MSG_STAT_ANY operation returns the identifier of the queue whose index was given in msqid.

On failure, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

The argument cmd is equal to IPC_STAT or MSG_STAT, but the calling process does not have read permission on the message queue msqid, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

The argument cmd has the value IPC_SET or IPC_STAT, but the address pointed to by buf isn't accessible.

EIDRM

The message queue was removed.

EINVAL

Invalid value for cmd or msqid. Or: for a MSG_STAT operation, the index value specified in msqid referred to an array slot that is currently unused.

EPERM

The argument cmd has the value IPC_SET or IPC_RMID, but the effective user ID of the calling process is not the creator (as found in msg_perm.cuid) or the owner (as found in msg_perm.uid) of the message queue, and the caller is not privileged (Linux: does not have the CAP_SYS_ADMIN capability).

EPERM

An attempt (IPC_SET) was made to increase msg_qbytes beyond the system parameter MSGMNB, but the caller is not privileged (Linux: does not have the CAP_SYS_RESOURCE capability).

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

Various fields in the struct msqid_ds were typed as short under Linux 2.2 and have become long under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.)

## NOTES
The IPC_INFO, MSG_STAT, and MSG_INFO operations are used by the ipcs(1) program to provide information on allocated resources. In the future these may modified or moved to a /proc filesystem interface.

## SEE ALSO
msgget(2), msgrcv(2), msgsnd(2), capabilities(7), mq_overview(7), sysvipc(7)


msgget

package: man-pages

title: msgget(2)

summary: get a System V message queue identifier

text:
# msgget(2)

## NAME
msgget - get a System V message queue identifier

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

## SYNOPSIS

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

```
int msgget(key_t key, int msgflg);
```

## DESCRIPTION
The msgget() system call returns the System V message queue identifier associated with the value of the key argument. It may be used either to obtain the identifier of a previously created message queue (when msgflg is zero and key does not have the value IPC_PRIVATE), or to create a new set.

A new message queue is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no message queue with the given key key exists, and IPC_CREAT is specified in msgflg.

If msgflg specifies both IPC_CREAT and IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

Upon creation, the least significant bits of the argument msgflg define the permissions of the message queue. These permission bits have the same format and semantics as the permissions specified for the mode argument of open(2). (The execute permissions are not used.)

If a new message queue is created, then its associated data structure msqid_ds (see msgctl(2)) is initialized as follows:

•

msg_perm.cuid and msg_perm.uid are set to the effective user ID of the calling process.

•

msg_perm.cgid and msg_perm.gid are set to the effective group ID of the calling process.

•

The least significant 9 bits of msg_perm.mode are set to the least significant 9 bits of msgflg.

•

msg_qnum, msg_lspid, msg_lrpid, msg_stime, and msg_rtime are set to 0.

•

msg_ctime is set to the current time.

•

msg_qbytes is set to the system limit MSGMNB.

If the message queue already exists the permissions are verified, and a check is made to see if it is marked for destruction.

## RETURN VALUE
On success, msgget() returns the message queue identifier (a nonnegative integer). On failure, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

A message queue exists for key, but the calling process does not have permission to access the queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EEXIST

IPC_CREAT and IPC_EXCL were specified in msgflg, but a message queue already exists for key.

ENOENT

No message queue exists for key and msgflg did not specify IPC_CREAT.

ENOMEM

A message queue has to be created but the system does not have enough memory for the new data structure.

ENOSPC

A message queue has to be created but the system limit for the maximum number of message queues (MSGMNI) would be exceeded.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

### Linux
Until Linux 2.3.20, Linux would return EIDRM for a msgget() on a message queue scheduled for deletion.

## NOTES
IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores everything but the least significant 9 bits of msgflg and creates a new message queue (on success).

The following is a system limit on message queue resources affecting a msgget() call:

MSGMNI

System-wide limit on the number of message queues. Before Linux 3.19, the default value for this limit was calculated using a formula based on available system memory. Since Linux 3.19, the default value is 32,000. On Linux, this limit can be read and modified via /proc/sys/kernel/msgmni.

## BUGS
The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would more clearly show its function.

## SEE ALSO
msgctl(2), msgrcv(2), msgsnd(2), ftok(3), capabilities(7), mq_overview(7), sysvipc(7)

branch: sisyphus


msgop

title: msgop(2)

summary: System V message queue operations

text:
# msgop(2)

## NAME
msgrcv, msgsnd - System V message queue operations

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

## SYNOPSIS

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

```
int msgsnd(int msqid, const void msgp[.msgsz], size_t msgsz,
               int msgflg);
```

```
ssize_t msgrcv(int msqid, void msgp[.msgsz], size_t msgsz, long msgtyp,
               int msgflg);
```

## DESCRIPTION
The msgsnd() and msgrcv() system calls are used to send messages to, and receive messages from, a System V message queue. The calling process must have write permission on the message queue in order to send a message, and read permission to receive a message.

The msgp argument is a pointer to a caller-defined structure of the following general form:

```
struct msgbuf {

    long mtype;       /* message type, must be > 0 */

    char mtext[1];    /* message data */
};
```

The mtext field is an array (or other structure) whose size is specified by msgsz, a nonnegative integer value. Messages of zero length (i.e., no mtext field) are permitted. The mtype field must have a strictly positive integer value. This value can be used by the receiving process for message selection (see the description of msgrcv() below).

### msgsnd()
The msgsnd() system call appends a copy of the message pointed to by msgp to the message queue whose identifier is specified by msqid.

If sufficient space is available in the queue, msgsnd() succeeds immediately. The queue capacity is governed by the msg_qbytes field in the associated data structure for the message queue. During queue creation this field is initialized to MSGMNB bytes, but this limit can be modified using msgctl(2). A message queue is considered to be full if either of the following conditions is true:

•

Adding a new message to the queue would cause the total number of bytes in the queue to exceed the queue's maximum size (the msg_qbytes field).

•

Adding another message to the queue would cause the total number of messages in the queue to exceed the queue's maximum size (the msg_qbytes field). This check is necessary to prevent an unlimited number of zero-length messages being placed on the queue. Although such messages contain no data, they nevertheless consume (locked) kernel memory.

If insufficient space is available in the queue, then the default behavior of msgsnd() is to block until space becomes available. If IPC_NOWAIT is specified in msgflg, then the call instead fails with the error EAGAIN.

A blocked msgsnd() call may also fail if:

•

the queue is removed, in which case the system call fails with errno set to EIDRM; or

•

a signal is caught, in which case the system call fails with errno set to EINTR;see signal(7). (msgsnd() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.)

Upon successful completion the message queue data structure is updated as follows:

•

msg_lspid is set to the process ID of the calling process.

•

msg_qnum is incremented by 1.

•

msg_stime is set to the current time.

### msgrcv()
The msgrcv() system call removes a message from the queue specified by msqid and places it in the buffer pointed to by msgp.

The argument msgsz specifies the maximum size in bytes for the member mtext of the structure pointed to by the msgp argument. If the message text has length greater than msgsz, then the behavior depends on whether MSG_NOERROR is specified in msgflg. If MSG_NOERROR is specified, then the message text will be truncated (and the truncated part will be lost); if MSG_NOERROR is not specified, then the message isn't removed from the queue and the system call fails returning -1 with errno set to E2BIG.

Unless MSG_COPY is specified in msgflg (see below), the msgtyp argument specifies the type of message requested, as follows:

•

If msgtyp is 0, then the first message in the queue is read.

•

If msgtyp is greater than 0, then the first message in the queue of type msgtyp is read, unless MSG_EXCEPT was specified in msgflg, in which case the first message in the queue of type not equal to msgtyp will be read.

•

If msgtyp is less than 0, then the first message in the queue with the lowest type less than or equal to the absolute value of msgtyp will be read.

The msgflg argument is a bit mask constructed by ORing together zero or more of the following flags:

IPC_NOWAIT

Return immediately if no message of the requested type is in the queue. The system call fails with errno set to ENOMSG.

MSG_COPY (since Linux 3.8)

Nondestructively fetch a copy of the message at the ordinal position in the queue specified by msgtyp (messages are considered to be numbered starting at 0).

This flag must be specified in conjunction with IPC_NOWAIT, with the result that, if there is no message available at the given position, the call fails immediately with the error ENOMSG. Because they alter the meaning of msgtyp in orthogonal ways, MSG_COPY and MSG_EXCEPT may not both be specified in msgflg.

The MSG_COPY flag was added for the implementation of the kernel checkpoint-restore facility and is available only if the kernel was built with the CONFIG_CHECKPOINT_RESTORE option.

MSG_EXCEPT

Used with msgtyp greater than 0 to read the first message in the queue with message type that differs from msgtyp.

MSG_NOERROR

To truncate the message text if longer than msgsz bytes.

If no message of the requested type is available and IPC_NOWAIT isn't specified in msgflg, the calling process is blocked until one of the following conditions occurs:

•

A message of the desired type is placed in the queue.

•

The message queue is removed from the system. In this case, the system call fails with errno set to EIDRM.

•

The calling process catches a signal. In this case, the system call fails with errno set to EINTR. (msgrcv() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.)

Upon successful completion the message queue data structure is updated as follows:

msg_lrpid is set to the process ID of the calling process.

msg_qnum is decremented by 1.

msg_rtime is set to the current time.

## RETURN VALUE
On success, msgsnd() returns 0 and msgrcv() returns the number of bytes actually copied into the mtext array. On failure, both functions return -1, and set errno to indicate the error.

## ERRORS
msgsnd() can fail with the following errors:

EACCES

The calling process does not have write permission on the message queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EAGAIN

The message can't be sent due to the msg_qbytes limit for the queue and IPC_NOWAIT was specified in msgflg.

EFAULT

The address pointed to by msgp isn't accessible.

EIDRM

The message queue was removed.

EINTR

Sleeping on a full message queue condition, the process caught a signal.

EINVAL

Invalid msqid value, or nonpositive mtype value, or invalid msgsz value (less than 0 or greater than the system value MSGMAX).

ENOMEM

The system does not have enough memory to make a copy of the message pointed to by msgp.

msgrcv() can fail with the following errors:

E2BIG

The message text length is greater than msgsz and MSG_NOERROR isn't specified in msgflg.

EACCES

The calling process does not have read permission on the message queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

The address pointed to by msgp isn't accessible.

EIDRM

While the process was sleeping to receive a message, the message queue was removed.

EINTR

While the process was sleeping to receive a message, the process caught a signal; see signal(7).

EINVAL

msqid was invalid, or msgsz was less than 0.

EINVAL (since Linux 3.14)

msgflg specified MSG_COPY, but not IPC_NOWAIT.

EINVAL (since Linux 3.14)

msgflg specified both MSG_COPY and MSG_EXCEPT.

ENOMSG

IPC_NOWAIT was specified in msgflg and no message of the requested type existed on the message queue.

ENOMSG

IPC_NOWAIT and MSG_COPY were specified in msgflg and the queue contains less than msgtyp messages.

ENOSYS (since Linux 3.8)

Both MSG_COPY and IPC_NOWAIT were specified in msgflg, and this kernel was configured without CONFIG_CHECKPOINT_RESTORE.

## STANDARDS
POSIX.1-2008.

The MSG_EXCEPT and MSG_COPY flags are Linux-specific; their definitions can be obtained by defining the _GNU_SOURCE feature test macro.

## HISTORY
POSIX.1-2001, SVr4.

The msgp argument is declared as struct msgbuf * in glibc 2.0 and 2.1. It is declared as void * in glibc 2.2 and later, as required by SUSv2 and SUSv3.

## NOTES
The following limits on message queue resources affect the msgsnd() call:

MSGMAX

Maximum size of a message text, in bytes (default value: 8192 bytes). On Linux, this limit can be read and modified via /proc/sys/kernel/msgmax.

MSGMNB

Maximum number of bytes that can be held in a message queue (default value: 16384 bytes). On Linux, this limit can be read and modified via /proc/sys/kernel/msgmnb. A privileged process (Linux: a process with the CAP_SYS_RESOURCE capability) can increase the size of a message queue beyond MSGMNB using the msgctl(2) IPC_SET operation.

The implementation has no intrinsic system-wide limits on the number of message headers (MSGTQL) and the number of bytes in the message pool (MSGPOOL).

## BUGS
In Linux 3.13 and earlier, if msgrcv() was called with the MSG_COPY flag, but without IPC_NOWAIT, and the message queue contained less than msgtyp messages, then the call would block until the next message is written to the queue. At that point, the call would return a copy of the message, regardless of whether that message was at the ordinal position msgtyp. This bug is fixed in Linux 3.14.

Specifying both MSG_COPY and MSC_EXCEPT in msgflg is a logical error (since these flags impose different interpretations on msgtyp). In Linux 3.13 and earlier, this error was not diagnosed by msgrcv(). This bug is fixed in Linux 3.14.

## EXAMPLES
The program below demonstrates the use of msgsnd() and msgrcv().

The example program is first run with the -s option to send a message and then run again with the -r option to receive a message.

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

```
$ ./a.out -s
sent: a message at Wed Mar  4 16:25:45 2015
```

```
$ ./a.out -r
message received: a message at Wed Mar  4 16:25:45 2015
```

### Program source

```
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#include <unistd.h>
struct msgbuf {

    long mtype;

    char mtext[80];
};
static void
usage(char *prog_name, char *msg)
{

    if (msg != NULL)

        fputs(msg, stderr);

    fprintf(stderr, "Usage: %s [options]\n", prog_name);

    fprintf(stderr, "Options are:\n");

    fprintf(stderr, "-s        send message using msgsnd()\n");

    fprintf(stderr, "-r        read message using msgrcv()\n");

    fprintf(stderr, "-t        message type (default is 1)\n");

    fprintf(stderr, "-k        message queue key (default is 1234)\n");

    exit(EXIT_FAILURE);
}
static void
send_msg(int qid, int msgtype)
{

    time_t         t;

    struct msgbuf  msg;

    msg.mtype = msgtype;

    time(&t);

    snprintf(msg.mtext, sizeof(msg.mtext), "a message at %s",

             ctime(&t));

    if (msgsnd(qid, &msg, sizeof(msg.mtext),

               IPC_NOWAIT) == -1)

    {

        perror("msgsnd error");

        exit(EXIT_FAILURE);

    }

    printf("sent: %s\n", msg.mtext);
}
static void
get_msg(int qid, int msgtype)
{

    struct msgbuf msg;

    if (msgrcv(qid, &msg, sizeof(msg.mtext), msgtype,

               MSG_NOERROR | IPC_NOWAIT) == -1) {

        if (errno != ENOMSG) {

            perror("msgrcv");

            exit(EXIT_FAILURE);

        }

        printf("No message available for msgrcv()\n");

    } else {

        printf("message received: %s\n", msg.mtext);

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

    int  qid, opt;

    int  mode = 0;               /* 1 = send, 2 = receive */

    int  msgtype = 1;

    int  msgkey = 1234;

    while ((opt = getopt(argc, argv, "srt:k:")) != -1) {

        switch (opt) {

        case 's':

            mode = 1;

            break;

        case 'r':

            mode = 2;

            break;

        case 't':

            msgtype = atoi(optarg);

            if (msgtype <= 0)

                usage(argv[0], "-t option must be greater than 0\n");

            break;

        case 'k':

            msgkey = atoi(optarg);

            break;

        default:

            usage(argv[0], "Unrecognized option\n");

        }

    }

    if (mode == 0)

        usage(argv[0], "must use either -s or -r option\n");

    qid = msgget(msgkey, IPC_CREAT | 0666);

    if (qid == -1) {

        perror("msgget");

        exit(EXIT_FAILURE);

    }

    if (mode == 2)

        get_msg(qid, msgtype);

    else

        send_msg(qid, msgtype);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
msgctl(2), msgget(2), capabilities(7), mq_overview(7), sysvipc(7)


msync

title: msync(2)

summary: synchronize a file with a memory map

text:
# msync(2)

## NAME
msync - synchronize a file with a memory map

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

## SYNOPSIS

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

```
int msync(void addr[.length], size_t length, int flags);
```

## DESCRIPTION
msync() flushes changes made to the in-core copy of a file that was mapped into memory using mmap(2) back to the filesystem. Without use of this call, there is no guarantee that changes are written back before munmap(2) is called. To be more precise, the part of the file that corresponds to the memory area starting at addr and having length length is updated.

The flags argument should specify exactly one of MS_ASYNC and MS_SYNC, and may additionally include the MS_INVALIDATE bit. These bits have the following meanings:

MS_ASYNC

Specifies that an update be scheduled, but the call returns immediately.

MS_SYNC

Requests an update and waits for it to complete.

MS_INVALIDATE

Asks to invalidate other mappings of the same file (so that they can be updated with the fresh values just written).

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

## ERRORS
EBUSY

MS_INVALIDATE was specified in flags, and a memory lock exists for the specified address range.

EINVAL

addr is not a multiple of PAGESIZE; or any bit other than MS_ASYNC | MS_INVALIDATE | MS_SYNC is set in flags; or both MS_SYNC and MS_ASYNC are set in flags.

ENOMEM

The indicated memory (or part of it) was not mapped.

## VERSIONS
According to POSIX, either MS_SYNC or MS_ASYNC must be specified in flags, and indeed failure to include one of these flags will cause msync() to fail on some systems. However, Linux permits a call to msync() that specifies neither of these flags, with semantics that are (currently) equivalent to specifying MS_ASYNC. (Since Linux 2.6.19, MS_ASYNC is in fact a no-op, since the kernel properly tracks dirty pages and flushes them to storage as necessary.) Notwithstanding the Linux behavior, portable, future-proof applications should ensure that they specify either MS_SYNC or MS_ASYNC in flags.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001.

This call was introduced in Linux 1.3.21, and then used EFAULT instead of ENOMEM. In Linux 2.4.19, this was changed to the POSIX value ENOMEM.

On POSIX systems on which msync() is available, both _POSIX_MAPPED_FILES and _POSIX_SYNCHRONIZED_IO are defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

## SEE ALSO
mmap(2)

B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128–129 and 389–391.


nanosleep

title: nanosleep(2)

summary: high-resolution sleep

text:
# nanosleep(2)

## NAME
nanosleep - high-resolution sleep

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

## SYNOPSIS

```
#include <time.h>
```

```
int nanosleep(const struct timespec *req,
              struct timespec *_Nullable rem);
```

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

nanosleep():

```
    _POSIX_C_SOURCE >= 199309L
```

## DESCRIPTION
nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.

If the call is interrupted by a signal handler, nanosleep() returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep() again and complete the specified pause (but see NOTES).

The timespec(3) structure is used to specify intervals of time with nanosecond precision.

The value of the nanoseconds field must be in the range [0, 999999999].

Compared to sleep(3) and usleep(3), nanosleep() has the following advantages: it provides a higher resolution for specifying the sleep interval; POSIX.1 explicitly specifies that it does not interact with signals; and it makes the task of resuming a sleep that has been interrupted by a signal handler easier.

## RETURN VALUE
On successfully sleeping for the requested interval, nanosleep() returns 0. If the call is interrupted by a signal handler or encounters an error, then it returns -1, with errno set to indicate the error.

## ERRORS
EFAULT

Problem with copying information from user space.

EINTR

The pause has been interrupted by a signal that was delivered to the thread (see signal(7)). The remaining sleep time has been written into *rem so that the thread can easily call nanosleep() again and continue with the pause.

EINVAL

The value in the tv_nsec field was not in the range [0, 999999999] or tv_sec was negative.

## VERSIONS
POSIX.1 specifies that nanosleep() should measure time against the CLOCK_REALTIME clock. However, Linux measures the time using the CLOCK_MONOTONIC clock. This probably does not matter, since the POSIX.1 specification for clock_settime(2) says that discontinuous changes in CLOCK_REALTIME should not affect nanosleep():

Setting the value of the CLOCK_REALTIME clock via clock_settime(2) shall have no effect on threads that are blocked waiting for a relative time service based upon this clock, including the nanosleep() function; ... Consequently, these time services shall expire when the requested relative interval elapses, independently of the new or old value of the clock.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001.

In order to support applications requiring much more precise pauses (e.g., in order to control some time-critical hardware), nanosleep() would handle pauses of up to 2 milliseconds by busy waiting with microsecond precision when called from a thread scheduled under a real-time policy like SCHED_FIFO or SCHED_RR. This special extension was removed in Linux 2.5.39, and is thus not available in Linux 2.6.0 and later kernels.

## NOTES
If the interval specified in req is not an exact multiple of the granularity underlying clock (see time(7)), then the interval will be rounded up to the next multiple. Furthermore, after the sleep completes, there may still be a delay before the CPU becomes free to once again execute the calling thread.

The fact that nanosleep() sleeps for a relative interval can be problematic if the call is repeatedly restarted after being interrupted by signals, since the time between the interruptions and restarts of the call will lead to drift in the time when the sleep finally completes. This problem can be avoided by using clock_nanosleep(2) with an absolute time value.

## BUGS
If a program that catches signals and uses nanosleep() receives signals at a very high rate, then scheduling delays and rounding errors in the kernel's calculation of the sleep interval and the returned remain value mean that the remain value may steadily increase on successive restarts of the nanosleep() call. To avoid such problems, use clock_nanosleep(2) with the TIMER_ABSTIME flag to sleep to an absolute deadline.

In Linux 2.4, if nanosleep() is stopped by a signal (e.g., SIGTSTP), then the call fails with the error EINTR after the thread is resumed by a SIGCONT signal. If the system call is subsequently restarted, then the time that the thread spent in the stopped state is not counted against the sleep interval. This problem is fixed in Linux 2.6.0 and later kernels.

## SEE ALSO
clock_nanosleep(2), restart_syscall(2), sched_setscheduler(2), timer_create(2), sleep(3), timespec(3), usleep(3), time(7)


nfsservctl

title: nfsservctl(2)

summary: syscall interface to kernel nfs daemon

text:
# nfsservctl(2)

## NAME
nfsservctl - syscall interface to kernel nfs daemon

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

## SYNOPSIS

```
#include <linux/nfsd/syscall.h>
```

```
long nfsservctl(int cmd, struct nfsctl_arg *argp,
                union nfsctl_res *resp);
```

## DESCRIPTION
Note: Since Linux 3.1, this system call no longer exists. It has been replaced by a set of files in the nfsd filesystem; see nfsd(7).

```
/*

 * These are the commands understood by nfsctl().

 */
#define NFSCTL_SVC        0  /* This is a server process. */
#define NFSCTL_ADDCLIENT  1  /* Add an NFS client. */
#define NFSCTL_DELCLIENT  2  /* Remove an NFS client. */
#define NFSCTL_EXPORT     3  /* Export a filesystem. */
#define NFSCTL_UNEXPORT   4  /* Unexport a filesystem. */
#define NFSCTL_UGIDUPDATE 5  /* Update a client's UID/GID map

                                (only in Linux 2.4.x and earlier). */
#define NFSCTL_GETFH      6  /* Get a file handle (used by mountd(8))

                                (only in Linux 2.4.x and earlier). */
struct nfsctl_arg {

    int                       ca_version;     /* safeguard */

    union {

        struct nfsctl_svc     u_svc;

        struct nfsctl_client  u_client;

        struct nfsctl_export  u_export;

        struct nfsctl_uidmap  u_umap;

        struct nfsctl_fhparm  u_getfh;

        unsigned int          u_debug;

    } u;
}
union nfsctl_res {

        struct knfs_fh          cr_getfh;

        unsigned int            cr_debug;
};
```

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

## STANDARDS
Linux.

## HISTORY
Removed in Linux 3.1. Removed in glibc 2.28.

## SEE ALSO
nfsd(7)


nice

title: nice(2)

summary: change process priority

text:
# nice(2)

## NAME
nice - change process priority

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

## SYNOPSIS

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

```
int nice(int inc);
```

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

nice():

```
    _XOPEN_SOURCE

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

        || /* glibc <= 2.19: */ _BSD_SOURCE || _SVID_SOURCE
```

## DESCRIPTION
nice() adds inc to the nice value for the calling thread. (A higher nice value means a lower priority.)

The range of the nice value is +19 (low priority) to -20 (high priority). Attempts to set a nice value outside the range are clamped to the range.

Traditionally, only a privileged process could lower the nice value (i.e., set a higher priority). However, since Linux 2.6.12, an unprivileged process can decrease the nice value of a target process that has a suitable RLIMIT_NICE soft limit; see getrlimit(2) for details.

## RETURN VALUE
On success, the new nice value is returned (but see NOTES below). On error, -1 is returned, and errno is set to indicate the error.

A successful call can legitimately return -1. To detect an error, set errno to 0 before the call, and check whether it is nonzero after nice() returns -1.

## ERRORS
EPERM

The calling process attempted to increase its priority by supplying a negative inc but has insufficient privileges. Under Linux, the CAP_SYS_NICE capability is required. (But see the discussion of the RLIMIT_NICE resource limit in setrlimit(2).)

## VERSIONS

### C library/kernel differences
POSIX.1 specifies that nice() should return the new nice value. However, the raw Linux system call returns 0 on success. Likewise, the nice() wrapper function provided in glibc 2.2.3 and earlier returns 0 on success.

Since glibc 2.2.4, the nice() wrapper function provided by glibc provides conformance to POSIX.1 by calling getpriority(2) to obtain the new nice value, which is then returned to the caller.

## STANDARDS
POSIX.1-2008.

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

## NOTES
For further details on the nice value, see sched(7).

Note: the addition of the "autogroup" feature in Linux 2.6.38 means that the nice value no longer has its traditional effect in many circumstances. For details, see sched(7).

## SEE ALSO
nice(1), renice(1), fork(2), getpriority(2), getrlimit(2), setpriority(2), capabilities(7), sched(7)


open

title: open(2)

summary: open and possibly create a file

text:
# open(2)

## NAME
open, openat, creat - open and possibly create a file

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

## SYNOPSIS

```
#include <fcntl.h>
```

```
int open(const char *pathname, int flags, ...
           /* mode_t mode */ );
```

```
int creat(const char *pathname, mode_t mode);
```

```
int openat(int dirfd, const char *pathname, int flags, ...
           /* mode_t mode */ );
```

```
/* Documented separately, in openat2(2): */
int openat2(int dirfd, const char *pathname,
           const struct open_how *how, size_t size);
```

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

openat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
The open() system call opens the file specified by pathname. If the specified file does not exist, it may optionally (if O_CREAT is specified in flags) be created by open().

The return value of open() is a file descriptor, a small, nonnegative integer that is an index to an entry in the process's table of open file descriptors. The file descriptor is used in subsequent system calls (read(2), write(2), lseek(2), fcntl(2), etc.) to refer to the open file. The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

By default, the new file descriptor is set to remain open across an execve(2) (i.e., the FD_CLOEXEC file descriptor flag described in fcntl(2) is initially disabled); the O_CLOEXEC flag, described below, can be used to change this default. The file offset is set to the beginning of the file (see lseek(2)).

A call to open() creates a new open file description, an entry in the system-wide table of open files. The open file description records the file offset and the file status flags (see below). A file descriptor is a reference to an open file description; this reference is unaffected if pathname is subsequently removed or modified to refer to a different file. For further details on open file descriptions, see NOTES.

The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.

In addition, zero or more file creation flags and file status flags can be bitwise ORed in flags. The file creation flags are O_CLOEXEC, O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY, O_NOFOLLOW, O_TMPFILE, and O_TRUNC. The file status flags are all of the remaining flags listed below. The distinction between these two groups of flags is that the file creation flags affect the semantics of the open operation itself, while the file status flags affect the semantics of subsequent I/O operations. The file status flags can be retrieved and (in some cases) modified; see fcntl(2) for details.

The full list of file creation flags and file status flags is as follows:

O_APPEND

The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). The modification of the file offset and the write operation are performed as a single atomic step.

O_APPEND may lead to corrupted files on NFS filesystems if more than one process appends data to a file at once. This is because NFS does not support appending to a file, so the client kernel has to simulate it, which can't be done without a race condition.

O_ASYNC

Enable signal-driven I/O: generate a signal (SIGIO by default, but this can be changed via fcntl(2)) when input or output becomes possible on this file descriptor. This feature is available only for terminals, pseudoterminals, sockets, and (since Linux 2.6) pipes and FIFOs. See fcntl(2) for further details. See also BUGS, below.

O_CLOEXEC (since Linux 2.6.23)

Enable the close-on-exec flag for the new file descriptor. Specifying this flag permits a program to avoid additional fcntl(2) F_SETFD operations to set the FD_CLOEXEC flag.

Note that the use of this flag is essential in some multithreaded programs, because using a separate fcntl(2) F_SETFD operation to set the FD_CLOEXEC flag does not suffice to avoid race conditions where one thread opens a file descriptor and attempts to set its close-on-exec flag using fcntl(2) at the same time as another thread does a fork(2) plus execve(2). Depending on the order of execution, the race may lead to the file descriptor returned by open() being unintentionally leaked to the program executed by the child process created by fork(2). (This kind of race is in principle possible for any system call that creates a file descriptor whose close-on-exec flag should be set, and various other Linux system calls provide an equivalent of the O_CLOEXEC flag to deal with this problem.)

O_CREAT

If pathname does not exist, create it as a regular file.

The owner (user ID) of the new file is set to the effective user ID of the process.

The group ownership (group ID) of the new file is set either to the effective group ID of the process (System V semantics) or to the group ID of the parent directory (BSD semantics). On Linux, the behavior depends on whether the set-group-ID mode bit is set on the parent directory: if that bit is set, then BSD semantics apply; otherwise, System V semantics apply. For some filesystems, the behavior also depends on the bsdgroups and sysvgroups mount options described in mount(8).

The mode argument specifies the file mode bits to be applied when a new file is created. If neither O_CREAT nor O_TMPFILE is specified in flags, then mode is ignored (and can thus be specified as 0, or simply omitted). The mode argument must be supplied if O_CREAT or O_TMPFILE is specified in flags; if it is not supplied, some arbitrary bytes from the stack will be applied as the file mode.

The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask).

Note that mode applies only to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor.

The following symbolic constants are provided for mode:

S_IRWXU

00700 user (file owner) has read, write, and execute permission

S_IRUSR

00400 user has read permission

S_IWUSR

00200 user has write permission

S_IXUSR

00100 user has execute permission

S_IRWXG

00070 group has read, write, and execute permission

S_IRGRP

00040 group has read permission

S_IWGRP

00020 group has write permission

S_IXGRP

00010 group has execute permission

S_IRWXO

00007 others have read, write, and execute permission

S_IROTH

00004 others have read permission

S_IWOTH

00002 others have write permission

S_IXOTH

00001 others have execute permission

According to POSIX, the effect when other bits are set in mode is unspecified. On Linux, the following bits are also honored in mode:

S_ISUID

0004000 set-user-ID bit

S_ISGID

0002000 set-group-ID bit (see inode(7)).

S_ISVTX

0001000 sticky bit (see inode(7)).

O_DIRECT (since Linux 2.4.10)

Try to minimize cache effects of the I/O to and from this file. In general this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File I/O is done directly to/from user-space buffers. The O_DIRECT flag on its own makes an effort to transfer data synchronously, but does not give the guarantees of the O_SYNC flag that data and necessary metadata are transferred. To guarantee synchronous I/O, O_SYNC must be used in addition to O_DIRECT. See NOTES below for further discussion.

A semantically similar (but deprecated) interface for block devices is described in raw(8).

O_DIRECTORY

If pathname is not a directory, cause the open to fail. This flag was added in Linux 2.1.126, to avoid denial-of-service problems if opendir(3) is called on a FIFO or tape device.

O_DSYNC

Write operations on the file will complete according to the requirements of synchronized I/O data integrity completion.

By the time write(2) (and similar) return, the output data has been transferred to the underlying hardware, along with any file metadata that would be required to retrieve that data (i.e., as though each write(2) was followed by a call to fdatasync(2)). See NOTES below.

O_EXCL

Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists, then open() fails with the error EEXIST.

When these two flags are specified, symbolic links are not followed: if pathname is a symbolic link, then open() fails regardless of where the symbolic link points.

In general, the behavior of O_EXCL is undefined if it is used without O_CREAT. There is one exception: on Linux 2.6 and later, O_EXCL can be used without O_CREAT if pathname refers to a block device. If the block device is in use by the system (e.g., mounted), open() fails with the error EBUSY.

On NFS, O_EXCL is supported only when using NFSv3 or later on kernel 2.6 or later. In NFS environments where O_EXCL support is not provided, programs that rely on it for performing locking tasks will contain a race condition. Portable programs that want to perform atomic file locking using a lockfile, and need to avoid reliance on NFS support for O_EXCL, can create a unique file on the same filesystem (e.g., incorporating hostname and PID), and use link(2) to make a link to the lockfile. If link(2) returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.

O_LARGEFILE

(LFS) Allow files whose sizes cannot be represented in an off_t (but can be represented in an off64_t) to be opened. The _LARGEFILE64_SOURCE macro must be defined (before including any header files) in order to obtain this definition. Setting the _FILE_OFFSET_BITS feature test macro to 64 (rather than using O_LARGEFILE) is the preferred method of accessing large files on 32-bit systems (see feature_test_macros(7)).

O_NOATIME (since Linux 2.6.8)

Do not update the file last access time (st_atime in the inode) when the file is read(2).

This flag can be employed only if one of the following conditions is true:

•

The effective UID of the process matches the owner UID of the file.

•

The calling process has the CAP_FOWNER capability in its user namespace and the owner UID of the file has a mapping in the namespace.

This flag is intended for use by indexing or backup programs, where its use can significantly reduce the amount of disk activity. This flag may not be effective on all filesystems. One example is NFS, where the server maintains the access time.

O_NOCTTY

If pathname refers to a terminal device—see tty(4)—it will not become the process's controlling terminal even if the process does not have one.

O_NOFOLLOW

If the trailing component (i.e., basename) of pathname is a symbolic link, then the open fails, with the error ELOOP. Symbolic links in earlier components of the pathname will still be followed. (Note that the ELOOP error that can occur in this case is indistinguishable from the case where an open fails because there are too many symbolic links found while resolving components in the prefix part of the pathname.)

This flag is a FreeBSD extension, which was added in Linux 2.1.126, and has subsequently been standardized in POSIX.1-2008.

See also O_PATH below.

O_NONBLOCK or O_NDELAY

When possible, the file is opened in nonblocking mode. Neither the open() nor any subsequent I/O operations on the file descriptor which is returned will cause the calling process to wait.

Note that the setting of this flag has no effect on the operation of poll(2), select(2), epoll(7), and similar, since those interfaces merely inform the caller about whether a file descriptor is "ready", meaning that an I/O operation performed on the file descriptor with the O_NONBLOCK flag clear would not block.

Note that this flag has no effect for regular files and block devices; that is, I/O operations will (briefly) block when device activity is required, regardless of whether O_NONBLOCK is set. Since O_NONBLOCK semantics might eventually be implemented, applications should not depend upon blocking behavior when specifying this flag for regular files and block devices.

For the handling of FIFOs (named pipes), see also fifo(7). For a discussion of the effect of O_NONBLOCK in conjunction with mandatory file locks and with file leases, see fcntl(2).

O_PATH (since Linux 2.6.39)

Obtain a file descriptor that can be used for two purposes: to indicate a location in the filesystem tree and to perform operations that act purely at the file descriptor level. The file itself is not opened, and other file operations (e.g., read(2), write(2), fchmod(2), fchown(2), fgetxattr(2), ioctl(2), mmap(2)) fail with the error EBADF.

The following operations can be performed on the resulting file descriptor:

•

close(2).

•

fchdir(2), if the file descriptor refers to a directory (since Linux 3.5).

•

fstat(2) (since Linux 3.6).

•

fstatfs(2) (since Linux 3.12).

•

Duplicating the file descriptor (dup(2), fcntl(2) F_DUPFD, etc.).

•

Getting and setting file descriptor flags (fcntl(2) F_GETFD and F_SETFD).

•

Retrieving open file status flags using the fcntl(2) F_GETFL operation: the returned flags will include the bit O_PATH.

•

Passing the file descriptor as the dirfd argument of openat() and the other "*at()" system calls. This includes linkat(2) with AT_EMPTY_PATH (or via procfs using AT_SYMLINK_FOLLOW) even if the file is not a directory.

•

Passing the file descriptor to another process via a UNIX domain socket (see SCM_RIGHTS in unix(7)).

When O_PATH is specified in flags, flag bits other than O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored.

Opening a file or directory with the O_PATH flag requires no permissions on the object itself (but does require execute permission on the directories in the path prefix). Depending on the subsequent operation, a check for suitable file permissions may be performed (e.g., fchdir(2) requires execute permission on the directory referred to by its file descriptor argument). By contrast, obtaining a reference to a filesystem object by opening it with the O_RDONLY flag requires that the caller have read permission on the object, even when the subsequent operation (e.g., fchdir(2), fstat(2)) does not require read permission on the object.

If pathname is a symbolic link and the O_NOFOLLOW flag is also specified, then the call returns a file descriptor referring to the symbolic link. This file descriptor can be used as the dirfd argument in calls to fchownat(2), fstatat(2), linkat(2), and readlinkat(2) with an empty pathname to have the calls operate on the symbolic link.

If pathname refers to an automount point that has not yet been triggered, so no other filesystem is mounted on it, then the call returns a file descriptor referring to the automount directory without triggering a mount. fstatfs(2) can then be used to determine if it is, in fact, an untriggered automount point (.f_type == AUTOFS_SUPER_MAGIC).

One use of O_PATH for regular files is to provide the equivalent of POSIX.1's O_EXEC functionality. This permits us to open a file for which we have execute permission but not read permission, and then execute that file, with steps something like the following:

```
char buf[PATH_MAX];
fd = open("some_prog", O_PATH);
snprintf(buf, PATH_MAX, "/proc/self/fd/%d", fd);
execl(buf, "some_prog", (char *) NULL);

```

An O_PATH file descriptor can also be passed as the argument of fexecve(3).

O_SYNC

Write operations on the file will complete according to the requirements of synchronized I/O file integrity completion (by contrast with the synchronized I/O data integrity completion provided by O_DSYNC.)

By the time write(2) (or similar) returns, the output data and associated file metadata have been transferred to the underlying hardware (i.e., as though each write(2) was followed by a call to fsync(2)). See NOTES below.

O_TMPFILE (since Linux 3.11)

Create an unnamed temporary regular file. The pathname argument specifies a directory; an unnamed inode will be created in that directory's filesystem. Anything written to the resulting file will be lost when the last file descriptor is closed, unless the file is given a name.

O_TMPFILE must be specified with one of O_RDWR or O_WRONLY and, optionally, O_EXCL. If O_EXCL is not specified, then linkat(2) can be used to link the temporary file into the filesystem, making it permanent, using code like the following:

```
char path[PATH_MAX];
fd = open("/path/to/dir", O_TMPFILE | O_RDWR,

                        S_IRUSR | S_IWUSR);
/* File I/O on 'fd'... */
linkat(fd, "", AT_FDCWD, "/path/for/file", AT_EMPTY_PATH);
/* If the caller doesn't have the CAP_DAC_READ_SEARCH

   capability (needed to use AT_EMPTY_PATH with linkat(2)),

   and there is a proc(5) filesystem mounted, then the

   linkat(2) call above can be replaced with:
snprintf(path, PATH_MAX,  "/proc/self/fd/%d", fd);
linkat(AT_FDCWD, path, AT_FDCWD, "/path/for/file",

                        AT_SYMLINK_FOLLOW);
*/

```

In this case, the open() mode argument determines the file permission mode, as with O_CREAT.

Specifying O_EXCL in conjunction with O_TMPFILE prevents a temporary file from being linked into the filesystem in the above manner. (Note that the meaning of O_EXCL in this case is different from the meaning of O_EXCL otherwise.)

There are two main use cases for O_TMPFILE:

•

Improved tmpfile(3) functionality: race-free creation of temporary files that (1) are automatically deleted when closed; (2) can never be reached via any pathname; (3) are not subject to symlink attacks; and (4) do not require the caller to devise unique names.

•

Creating a file that is initially invisible, which is then populated with data and adjusted to have appropriate filesystem attributes (fchown(2), fchmod(2), fsetxattr(2), etc.) before being atomically linked into the filesystem in a fully formed state (using linkat(2) as described above).

O_TMPFILE requires support by the underlying filesystem; only a subset of Linux filesystems provide that support. In the initial implementation, support was provided in the ext2, ext3, ext4, UDF, Minix, and tmpfs filesystems. Support for other filesystems has subsequently been added as follows: XFS (Linux 3.15); Btrfs (Linux 3.16); F2FS (Linux 3.16); and ubifs (Linux 4.9)

O_TRUNC

If the file already exists and is a regular file and the access mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise, the effect of O_TRUNC is unspecified.

### creat()
A call to creat() is equivalent to calling open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.

### openat()
The openat() system call operates in exactly the same way as open(), except for the differences described here.

The dirfd argument is used in conjunction with the pathname argument as follows:

•

If the pathname given in pathname is absolute, then dirfd is ignored.

•

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

•

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by open() for a relative pathname). In this case, dirfd must be a directory that was opened for reading (O_RDONLY) or using the O_PATH flag.

If the pathname given in pathname is relative, and dirfd is not a valid file descriptor, an error (EBADF) results. (Specifying an invalid file descriptor number in dirfd can be used as a means to ensure that pathname is absolute.)

### openat2(2)
The openat2(2) system call is an extension of openat(), and provides a superset of the features of openat(). It is documented separately, in openat2(2).

## RETURN VALUE
On success, open(), openat(), and creat() return the new file descriptor (a nonnegative integer). On error, -1 is returned and errno is set to indicate the error.

## ERRORS
open(), openat(), and creat() can fail with the following errors:

EACCES

The requested access to the file is not allowed, or search permission is denied for one of the directories in the path prefix of pathname, or the file did not exist yet and write access to the parent directory is not allowed. (See also path_resolution(7).)

EACCES

Where O_CREAT is specified, the protected_fifos or protected_regular sysctl is enabled, the file already exists and is a FIFO or regular file, the owner of the file is neither the current user nor the owner of the containing directory, and the containing directory is both world- or group-writable and sticky. For details, see the descriptions of /proc/sys/fs/protected_fifos and /proc/sys/fs/protected_regular in proc(5).

EBADF

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

EBUSY

O_EXCL was specified in flags and pathname refers to a block device that is in use by the system (e.g., it is mounted).

EDQUOT

Where O_CREAT is specified, the file does not exist, and the user's quota of disk blocks or inodes on the filesystem has been exhausted.

EEXIST

pathname already exists and O_CREAT and O_EXCL were used.

EFAULT

pathname points outside your accessible address space.

EFBIG

See EOVERFLOW.

EINTR

While blocked waiting to complete an open of a slow device (e.g., a FIFO; see fifo(7)), the call was interrupted by a signal handler; see signal(7).

EINVAL

The filesystem does not support the O_DIRECT flag. See NOTES for more information.

EINVAL

Invalid value in flags.

EINVAL

O_TMPFILE was specified in flags, but neither O_WRONLY nor O_RDWR was specified.

EINVAL

O_CREAT was specified in flags and the final component ("basename") of the new file's pathname is invalid (e.g., it contains characters not permitted by the underlying filesystem).

EINVAL

The final component ("basename") of pathname is invalid (e.g., it contains characters not permitted by the underlying filesystem).

EISDIR

pathname refers to a directory and the access requested involved writing (that is, O_WRONLY or O_RDWR is set).

EISDIR

pathname refers to an existing directory, O_TMPFILE and one of O_WRONLY or O_RDWR were specified in flags, but this kernel version does not provide the O_TMPFILE functionality.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ELOOP

pathname was a symbolic link, and flags specified O_NOFOLLOW but not O_PATH.

EMFILE

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

ENAMETOOLONG

pathname was too long.

ENFILE

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

ENODEV

pathname refers to a device special file and no corresponding device exists. (This is a Linux kernel bug; in this situation ENXIO must be returned.)

ENOENT

O_CREAT is not set and the named file does not exist.

ENOENT

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

ENOENT

pathname refers to a nonexistent directory, O_TMPFILE and one of O_WRONLY or O_RDWR were specified in flags, but this kernel version does not provide the O_TMPFILE functionality.

ENOMEM

The named file is a FIFO, but memory for the FIFO buffer can't be allocated because the per-user hard limit on memory allocation for pipes has been reached and the caller is not privileged; see pipe(7).

ENOMEM

Insufficient kernel memory was available.

ENOSPC

pathname was to be created but the device containing pathname has no room for the new file.

ENOTDIR

A component used as a directory in pathname is not, in fact, a directory, or O_DIRECTORY was specified and pathname was not a directory.

ENOTDIR

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

ENXIO

O_NONBLOCK | O_WRONLY is set, the named file is a FIFO, and no process has the FIFO open for reading.

ENXIO

The file is a device special file and no corresponding device exists.

ENXIO

The file is a UNIX domain socket.

EOPNOTSUPP

The filesystem containing pathname does not support O_TMPFILE.

EOVERFLOW

pathname refers to a regular file that is too large to be opened. The usual scenario here is that an application compiled on a 32-bit platform without -D_FILE_OFFSET_BITS=64 tried to open a file whose size exceeds (1<<31)-1 bytes; see also O_LARGEFILE above. This is the error specified by POSIX.1; before Linux 2.6.24, Linux gave the error EFBIG for this case.

EPERM

The O_NOATIME flag was specified, but the effective user ID of the caller did not match the owner of the file and the caller was not privileged.

EPERM

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

EROFS

pathname refers to a file on a read-only filesystem and write access was requested.

ETXTBSY

pathname refers to an executable image which is currently being executed and write access was requested.

ETXTBSY

pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.

ETXTBSY

pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.

EWOULDBLOCK

The O_NONBLOCK flag was specified, and an incompatible lease was held on the file (see fcntl(2)).

## VERSIONS
The (undefined) effect of O_RDONLY | O_TRUNC varies among implementations. On many systems the file is actually truncated.

### Synchronized I/O
The POSIX.1-2008 "synchronized I/O" option specifies different variants of synchronized I/O, and specifies the open() flags O_SYNC, O_DSYNC, and O_RSYNC for controlling the behavior. Regardless of whether an implementation supports this option, it must at least support the use of O_SYNC for regular files.

Linux implements O_SYNC and O_DSYNC, but not O_RSYNC. Somewhat incorrectly, glibc defines O_RSYNC to have the same value as O_SYNC. (O_RSYNC is defined in the Linux header file <asm/fcntl.h> on HP PA-RISC, but it is not used.)

O_SYNC provides synchronized I/O file integrity completion, meaning write operations will flush data and all associated metadata to the underlying hardware. O_DSYNC provides synchronized I/O data integrity completion, meaning write operations will flush data to the underlying hardware, but will only flush metadata updates that are required to allow a subsequent read operation to complete successfully. Data integrity completion can reduce the number of disk operations that are required for applications that don't need the guarantees of file integrity completion.

To understand the difference between the two types of completion, consider two pieces of file metadata: the file last modification timestamp (st_mtime) and the file length. All write operations will update the last file modification timestamp, but only writes that add data to the end of the file will change the file length. The last modification timestamp is not needed to ensure that a read completes successfully, but the file length is. Thus, O_DSYNC would only guarantee to flush updates to the file length metadata (whereas O_SYNC would also always flush the last modification timestamp metadata).

Before Linux 2.6.33, Linux implemented only the O_SYNC flag for open(). However, when that flag was specified, most filesystems actually provided the equivalent of synchronized I/O data integrity completion (i.e., O_SYNC was actually implemented as the equivalent of O_DSYNC).

Since Linux 2.6.33, proper O_SYNC support is provided. However, to ensure backward binary compatibility, O_DSYNC was defined with the same value as the historical O_SYNC, and O_SYNC was defined as a new (two-bit) flag value that includes the O_DSYNC flag value. This ensures that applications compiled against new headers get at least O_DSYNC semantics before Linux 2.6.33.

### C library/kernel differences
Since glibc 2.26, the glibc wrapper function for open() employs the openat() system call, rather than the kernel's open() system call. For certain architectures, this is also true before glibc 2.26.

## STANDARDS
open()

creat()

openat()

POSIX.1-2008.

openat2(2) Linux.

The O_DIRECT, O_NOATIME, O_PATH, and O_TMPFILE flags are Linux-specific. One must define _GNU_SOURCE to obtain their definitions.

The O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW flags are not specified in POSIX.1-2001, but are specified in POSIX.1-2008. Since glibc 2.12, one can obtain their definitions by defining either _POSIX_C_SOURCE with a value greater than or equal to 200809L or _XOPEN_SOURCE with a value greater than or equal to 700. In glibc 2.11 and earlier, one obtains the definitions by defining _GNU_SOURCE.

## HISTORY
open()

creat()

SVr4, 4.3BSD, POSIX.1-2001.

openat()

POSIX.1-2008. Linux 2.6.16, glibc 2.4.

## NOTES
Under Linux, the O_NONBLOCK flag is sometimes used in cases where one wants to open but does not necessarily have the intention to read or write. For example, this may be used to open a device in order to get a file descriptor for use with ioctl(2).

Note that open() can open device special files, but creat() cannot create them; use mknod(2) instead.

If the file is newly created, its st_atime, st_ctime, st_mtime fields (respectively, time of last access, time of last status change, and time of last modification; see stat(2)) are set to the current time, and so are the st_ctime and st_mtime fields of the parent directory. Otherwise, if the file is modified because of the O_TRUNC flag, its st_ctime and st_mtime fields are set to the current time.

The files in the /proc/pid/fd directory show the open file descriptors of the process with the PID pid. The files in the /proc/pid/fdinfo directory show even more information about these file descriptors. See proc(5) for further details of both of these directories.

The Linux header file <asm/fcntl.h> doesn't define O_ASYNC; the (BSD-derived) FASYNC synonym is defined instead.

### Open file descriptions
The term open file description is the one used by POSIX to refer to the entries in the system-wide table of open files. In other contexts, this object is variously also called an "open file object", a "file handle", an "open file table entry", or—in kernel-developer parlance—a struct file.

When a file descriptor is duplicated (using dup(2) or similar), the duplicate refers to the same open file description as the original file descriptor, and the two file descriptors consequently share the file offset and file status flags. Such sharing can also occur between processes: a child process created via fork(2) inherits duplicates of its parent's file descriptors, and those duplicates refer to the same open file descriptions.

Each open() of a file creates a new open file description; thus, there may be multiple open file descriptions corresponding to a file inode.

On Linux, one can use the kcmp(2) KCMP_FILE operation to test whether two file descriptors (in the same process or in two different processes) refer to the same open file description.

### NFS
There are many infelicities in the protocol underlying NFS, affecting amongst others O_SYNC and O_NDELAY.

On NFS filesystems with UID mapping enabled, open() may return a file descriptor but, for example, read(2) requests are denied with EACCES. This is because the client performs open() by checking the permissions, but UID mapping is performed by the server upon read and write requests.

### FIFOs
Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread). See fifo(7) for further details.

### File access mode
Unlike the other values that can be specified in flags, the access mode values O_RDONLY, O_WRONLY, and O_RDWR do not specify individual bits. Rather, they define the low order two bits of flags, and are defined respectively as 0, 1, and 2. In other words, the combination O_RDONLY | O_WRONLY is a logical error, and certainly does not have the same meaning as O_RDWR.

Linux reserves the special, nonstandard access mode 3 (binary 11) in flags to mean: check for read and write permission on the file and return a file descriptor that can't be used for reading or writing. This nonstandard access mode is used by some Linux drivers to return a file descriptor that is to be used only for device-specific ioctl(2) operations.

### Rationale for openat() and other directory file descriptor APIs
openat() and the other system calls and library functions that take a directory file descriptor argument (i.e., execveat(2), faccessat(2), fanotify_mark(2), fchmodat(2), fchownat(2), fspick(2), fstatat(2), futimesat(2), linkat(2), mkdirat(2), mknodat(2), mount_setattr(2), move_mount(2), name_to_handle_at(2), open_tree(2), openat2(2), readlinkat(2), renameat(2), renameat2(2), statx(2), symlinkat(2), unlinkat(2), utimensat(2), mkfifoat(3), and scandirat(3)) address two problems with the older interfaces that preceded them. Here, the explanation is in terms of the openat() call, but the rationale is analogous for the other interfaces.

First, openat() allows an application to avoid race conditions that could occur when using open() to open files in directories other than the current working directory. These race conditions result from the fact that some component of the directory prefix given to open() could be changed in parallel with the call to open(). Suppose, for example, that we wish to create the file dir1/dir2/xxx.dep if the file dir1/dir2/xxx exists. The problem is that between the existence check and the file-creation step, dir1 or dir2 (which might be symbolic links) could be modified to point to a different location. Such races can be avoided by opening a file descriptor for the target directory, and then specifying that file descriptor as the dirfd argument of (say) fstatat(2) and openat(). The use of the dirfd file descriptor also has other benefits:

•

the file descriptor is a stable reference to the directory, even if the directory is renamed; and

•

the open file descriptor prevents the underlying filesystem from being dismounted, just as when a process has a current working directory on a filesystem.

Second, openat() allows the implementation of a per-thread "current working directory", via file descriptor(s) maintained by the application. (This functionality can also be obtained by tricks based on the use of /proc/self/fd/dirfd, but less efficiently.)

The dirfd argument for these APIs can be obtained by using open() or openat() to open a directory (with either the O_RDONLY or the O_PATH flag). Alternatively, such a file descriptor can be obtained by applying dirfd(3) to a directory stream created using opendir(3).

When these APIs are given a dirfd argument of AT_FDCWD or the specified pathname is absolute, then they handle their pathname argument in the same way as the corresponding conventional APIs. However, in this case, several of the APIs have a flags argument that provides access to functionality that is not available with the corresponding conventional APIs.

### O_DIRECT
The O_DIRECT flag may impose alignment restrictions on the length and address of user-space buffers and the file offset of I/Os. In Linux alignment restrictions vary by filesystem and kernel version and might be absent entirely. The handling of misaligned O_DIRECT I/Os also varies; they can either fail with EINVAL or fall back to buffered I/O.

Since Linux 6.1, O_DIRECT support and alignment restrictions for a file can be queried using statx(2), using the STATX_DIOALIGN flag. Support for STATX_DIOALIGN varies by filesystem; see statx(2).

Some filesystems provide their own interfaces for querying O_DIRECT alignment restrictions, for example the XFS_IOC_DIOINFO operation in xfsctl(3). STATX_DIOALIGN should be used instead when it is available.

If none of the above is available, then direct I/O support and alignment restrictions can only be assumed from known characteristics of the filesystem, the individual file, the underlying storage device(s), and the kernel version. In Linux 2.4, most filesystems based on block devices require that the file offset and the length and memory address of all I/O segments be multiples of the filesystem block size (typically 4096 bytes). In Linux 2.6.0, this was relaxed to the logical block size of the block device (typically 512 bytes). A block device's logical block size can be determined using the ioctl(2) BLKSSZGET operation or from the shell using the command:

```
blockdev --getss
```

O_DIRECT I/Os should never be run concurrently with the fork(2) system call, if the memory buffer is a private mapping (i.e., any mapping created with the mmap(2) MAP_PRIVATE flag; this includes memory allocated on the heap and statically allocated buffers). Any such I/Os, whether submitted via an asynchronous I/O interface or from another thread in the process, should be completed before fork(2) is called. Failure to do so can result in data corruption and undefined behavior in parent and child processes. This restriction does not apply when the memory buffer for the O_DIRECT I/Os was created using shmat(2) or mmap(2) with the MAP_SHARED flag. Nor does this restriction apply when the memory buffer has been advised as MADV_DONTFORK with madvise(2), ensuring that it will not be available to the child after fork(2).

The O_DIRECT flag was introduced in SGI IRIX, where it has alignment restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2) call to query appropriate alignments, and sizes. FreeBSD 4.x introduced a flag of the same name, but without alignment restrictions.

O_DIRECT support was added in Linux 2.4.10. Older Linux kernels simply ignore this flag. Some filesystems may not implement the flag, in which case open() fails with the error EINVAL if it is used.

Applications should avoid mixing O_DIRECT and normal I/O to the same file, and especially to overlapping byte regions in the same file. Even when the filesystem correctly handles the coherency issues in this situation, overall I/O throughput is likely to be slower than using either mode alone. Likewise, applications should avoid mixing mmap(2) of files with direct I/O to the same files.

The behavior of O_DIRECT with NFS will differ from local filesystems. Older kernels, or kernels configured in certain ways, may not support this combination. The NFS protocol does not support passing the flag to the server, so O_DIRECT I/O will bypass the page cache only on the client; the server may still cache the I/O. The client asks the server to make the I/O synchronous to preserve the synchronous semantics of O_DIRECT. Some servers will perform poorly under these circumstances, especially if the I/O size is small. Some servers may also be configured to lie to clients about the I/O having reached stable storage; this will avoid the performance penalty at some risk to data integrity in the event of server power failure. The Linux NFS client places no alignment restrictions on O_DIRECT I/O.

In summary, O_DIRECT is a potentially powerful tool that should be used with caution. It is recommended that applications treat use of O_DIRECT as a performance option which is disabled by default.

## BUGS
Currently, it is not possible to enable signal-driven I/O by specifying O_ASYNC when calling open(); use fcntl(2) to enable this flag.

One must check for two different error codes, EISDIR and ENOENT, when trying to determine whether the kernel supports O_TMPFILE functionality.

When both O_CREAT and O_DIRECTORY are specified in flags and the file specified by pathname does not exist, open() will create a regular file (i.e., O_DIRECTORY is ignored).

## SEE ALSO
chmod(2), chown(2), close(2), dup(2), fcntl(2), link(2), lseek(2), mknod(2), mmap(2), mount(2), open_by_handle_at(2), openat2(2), read(2), socket(2), stat(2), umask(2), unlink(2), write(2), fopen(3), acl(5), fifo(7), inode(7), path_resolution(7), symlink(7)


title: open_by_handle_at(2)

summary: obtain handle

text:
# open_by_handle_at(2)

## NAME
name_to_handle_at, open_by_handle_at - obtain handle for a pathname and open file via a handle

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

## SYNOPSIS

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

```
int name_to_handle_at(int dirfd, const char *pathname,
                      struct file_handle *handle,
                      int *mount_id, int flags);
int open_by_handle_at(int mount_fd, struct file_handle *handle,
                      int flags);
```

## DESCRIPTION
The name_to_handle_at() and open_by_handle_at() system calls split the functionality of openat(2) into two parts: name_to_handle_at() returns an opaque handle that corresponds to a specified file; open_by_handle_at() opens the file corresponding to a handle returned by a previous call to name_to_handle_at() and returns an open file descriptor.

### name_to_handle_at()
The name_to_handle_at() system call returns a file handle and a mount ID corresponding to the file specified by the dirfd and pathname arguments. The file handle is returned via the argument handle, which is a pointer to a structure of the following form:

```
struct file_handle {

    unsigned int  handle_bytes;   /* Size of f_handle [in, out] */

    int           handle_type;    /* Handle type [out] */

    unsigned char f_handle[0];    /* File identifier (sized by

                                     caller) [out] */
};
```

It is the caller's responsibility to allocate the structure with a size large enough to hold the handle returned in f_handle. Before the call, the handle_bytes field should be initialized to contain the allocated size for f_handle. (The constant MAX_HANDLE_SZ, defined in <fcntl.h>, specifies the maximum expected size for a file handle. It is not a guaranteed upper limit as future filesystems may require more space.) Upon successful return, the handle_bytes field is updated to contain the number of bytes actually written to f_handle.

The caller can discover the required size for the file_handle structure by making a call in which handle->handle_bytes is zero; in this case, the call fails with the error EOVERFLOW and handle->handle_bytes is set to indicate the required size; the caller can then use this information to allocate a structure of the correct size (see EXAMPLES below). Some care is needed here as EOVERFLOW can also indicate that no file handle is available for this particular name in a filesystem which does normally support file-handle lookup. This case can be detected when the EOVERFLOW error is returned without handle_bytes being increased.

Other than the use of the handle_bytes field, the caller should treat the file_handle structure as an opaque data type: the handle_type and f_handle fields are needed only by a subsequent call to open_by_handle_at().

The flags argument is a bit mask constructed by ORing together zero or more of AT_EMPTY_PATH and AT_SYMLINK_FOLLOW, described below.

Together, the pathname and dirfd arguments identify the file for which a handle is to be obtained. There are four distinct cases:

•

If pathname is a nonempty string containing an absolute pathname, then a handle is returned for the file referred to by that pathname. In this case, dirfd is ignored.

•

If pathname is a nonempty string containing a relative pathname and dirfd has the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the caller, and a handle is returned for the file to which it refers.

•

If pathname is a nonempty string containing a relative pathname and dirfd is a file descriptor referring to a directory, then pathname is interpreted relative to the directory referred to by dirfd, and a handle is returned for the file to which it refers. (See openat(2) for an explanation of why "directory file descriptors" are useful.)

•

If pathname is an empty string and flags specifies the value AT_EMPTY_PATH, then dirfd can be an open file descriptor referring to any type of file, or AT_FDCWD, meaning the current working directory, and a handle is returned for the file to which it refers.

The mount_id argument returns an identifier for the filesystem mount that corresponds to pathname. This corresponds to the first field in one of the records in /proc/self/mountinfo. Opening the pathname in the fifth field of that record yields a file descriptor for the mount point; that file descriptor can be used in a subsequent call to open_by_handle_at(). mount_id is returned both for a successful call and for a call that results in the error EOVERFLOW.

By default, name_to_handle_at() does not dereference pathname if it is a symbolic link, and thus returns a handle for the link itself. If AT_SYMLINK_FOLLOW is specified in flags, pathname is dereferenced if it is a symbolic link (so that the call returns a handle for the file referred to by the link).

name_to_handle_at() does not trigger a mount when the final component of the pathname is an automount point. When a filesystem supports both file handles and automount points, a name_to_handle_at() call on an automount point will return with error EOVERFLOW without having increased handle_bytes. This can happen since Linux 4.13 with NFS when accessing a directory which is on a separate filesystem on the server. In this case, the automount can be triggered by adding a "/" to the end of the pathname.

### open_by_handle_at()
The open_by_handle_at() system call opens the file referred to by handle, a file handle returned by a previous call to name_to_handle_at().

The mount_fd argument is a file descriptor for any object (file, directory, etc.) in the mounted filesystem with respect to which handle should be interpreted. The special value AT_FDCWD can be specified, meaning the current working directory of the caller.

The flags argument is as for open(2). If handle refers to a symbolic link, the caller must specify the O_PATH flag, and the symbolic link is not dereferenced; the O_NOFOLLOW flag, if specified, is ignored.

The caller must have the CAP_DAC_READ_SEARCH capability to invoke open_by_handle_at().

## RETURN VALUE
On success, name_to_handle_at() returns 0, and open_by_handle_at() returns a file descriptor (a nonnegative integer).

In the event of an error, both system calls return -1 and set errno to indicate the error.

## ERRORS
name_to_handle_at() and open_by_handle_at() can fail for the same errors as openat(2). In addition, they can fail with the errors noted below.

name_to_handle_at() can fail with the following errors:

EFAULT

pathname, mount_id, or handle points outside your accessible address space.

EINVAL

flags includes an invalid bit value.

EINVAL

handle->handle_bytes is greater than MAX_HANDLE_SZ.

ENOENT

pathname is an empty string, but AT_EMPTY_PATH was not specified in flags.

ENOTDIR

The file descriptor supplied in dirfd does not refer to a directory, and it is not the case that both flags includes AT_EMPTY_PATH and pathname is an empty string.

EOPNOTSUPP

The filesystem does not support decoding of a pathname to a file handle.

EOVERFLOW

The handle->handle_bytes value passed into the call was too small. When this error occurs, handle->handle_bytes is updated to indicate the required size for the handle.

open_by_handle_at() can fail with the following errors:

EBADF

mount_fd is not an open file descriptor.

EBADF

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

EFAULT

handle points outside your accessible address space.

EINVAL

handle->handle_bytes is greater than MAX_HANDLE_SZ or is equal to zero.

ELOOP

handle refers to a symbolic link, but O_PATH was not specified in flags.

EPERM

The caller does not have the CAP_DAC_READ_SEARCH capability.

ESTALE

The specified handle is not valid. This error will occur if, for example, the file has been deleted.

## VERSIONS
FreeBSD has a broadly similar pair of system calls in the form of getfh() and openfh().

## STANDARDS
Linux.

## HISTORY
Linux 2.6.39, glibc 2.14.

## NOTES
A file handle can be generated in one process using name_to_handle_at() and later used in a different process that calls open_by_handle_at().

Some filesystem don't support the translation of pathnames to file handles, for example, /proc, /sys, and various network filesystems.

A file handle may become invalid ("stale") if a file is deleted, or for other filesystem-specific reasons. Invalid handles are notified by an ESTALE error from open_by_handle_at().

These system calls are designed for use by user-space file servers. For example, a user-space NFS server might generate a file handle and pass it to an NFS client. Later, when the client wants to open the file, it could pass the handle back to the server. This sort of functionality allows a user-space file server to operate in a stateless fashion with respect to the files it serves.

If pathname refers to a symbolic link and flags does not specify AT_SYMLINK_FOLLOW, then name_to_handle_at() returns a handle for the link (rather than the file to which it refers). The process receiving the handle can later perform operations on the symbolic link by converting the handle to a file descriptor using open_by_handle_at() with the O_PATH flag, and then passing the file descriptor as the dirfd argument in system calls such as readlinkat(2) and fchownat(2).

### Obtaining a persistent filesystem ID
The mount IDs in /proc/self/mountinfo can be reused as filesystems are unmounted and mounted. Therefore, the mount ID returned by name_to_handle_at() (in *mount_id) should not be treated as a persistent identifier for the corresponding mounted filesystem. However, an application can use the information in the mountinfo record that corresponds to the mount ID to derive a persistent identifier.

For example, one can use the device name in the fifth field of the mountinfo record to search for the corresponding device UUID via the symbolic links in /dev/disks/by-uuid. (A more comfortable way of obtaining the UUID is to use the libblkid(3) library.) That process can then be reversed, using the UUID to look up the device name, and then obtaining the corresponding mount point, in order to produce the mount_fd argument used by open_by_handle_at().

## EXAMPLES
The two programs below demonstrate the use of name_to_handle_at() and open_by_handle_at(). The first program (t_name_to_handle_at.c) uses name_to_handle_at() to obtain the file handle and mount ID for the file specified in its command-line argument; the handle and mount ID are written to standard output.

The second program (t_open_by_handle_at.c) reads a mount ID and file handle from standard input. The program then employs open_by_handle_at() to open the file using that handle. If an optional command-line argument is supplied, then the mount_fd argument for open_by_handle_at() is obtained by opening the directory named in that argument. Otherwise, mount_fd is obtained by scanning /proc/self/mountinfo to find a record whose mount ID matches the mount ID read from standard input, and the mount directory specified in that record is opened. (These programs do not deal with the fact that mount IDs are not persistent.)

The following shell session demonstrates the use of these two programs:

```
$ echo 'Can you please think about it?' > cecilia.txt
$ ./t_name_to_handle_at cecilia.txt > fh
$ ./t_open_by_handle_at < fh
open_by_handle_at: Operation not permitted
$ sudo ./t_open_by_handle_at < fh      # Need CAP_SYS_ADMIN
Read 31 bytes
$ rm cecilia.txt
```

Now we delete and (quickly) re-create the file so that it has the same content and (by chance) the same inode. Nevertheless, open_by_handle_at() recognizes that the original file referred to by the file handle no longer exists.

```
$ stat --printf="%i\n" cecilia.txt     # Display inode number
4072121
$ rm cecilia.txt
$ echo 'Can you please think about it?' > cecilia.txt
$ stat --printf="%i\n" cecilia.txt     # Check inode number
4072121
$ sudo ./t_open_by_handle_at < fh
open_by_handle_at: Stale NFS file handle
```

### Program source: t_name_to_handle_at.c

```
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{

    int                 mount_id, fhsize, flags, dirfd;

    char                *pathname;

    struct file_handle  *fhp;

    if (argc != 2) {

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

        exit(EXIT_FAILURE);

    }

    pathname = argv[1];

    /* Allocate file_handle structure. */

    fhsize = sizeof(*fhp);

    fhp = malloc(fhsize);

    if (fhp == NULL)

        err(EXIT_FAILURE, "malloc");

    /* Make an initial call to name_to_handle_at() to discover

       the size required for file handle. */

    dirfd = AT_FDCWD;           /* For name_to_handle_at() calls */

    flags = 0;                  /* For name_to_handle_at() calls */

    fhp->handle_bytes = 0;

    if (name_to_handle_at(dirfd, pathname, fhp,

                          &mount_id, flags) != -1

        || errno != EOVERFLOW)

    {

        fprintf(stderr, "Unexpected result from name_to_handle_at()\n");

        exit(EXIT_FAILURE);

    }

    /* Reallocate file_handle structure with correct size. */

    fhsize = sizeof(*fhp) + fhp->handle_bytes;

    fhp = realloc(fhp, fhsize);         /* Copies fhp->handle_bytes */

    if (fhp == NULL)

        err(EXIT_FAILURE, "realloc");

    /* Get file handle from pathname supplied on command line. */

    if (name_to_handle_at(dirfd, pathname, fhp, &mount_id, flags) == -1)

        err(EXIT_FAILURE, "name_to_handle_at");

    /* Write mount ID, file handle size, and file handle to stdout,

       for later reuse by t_open_by_handle_at.c. */

    printf("%d\n", mount_id);

    printf("%u %d   ", fhp->handle_bytes, fhp->handle_type);

    for (size_t j = 0; j < fhp->handle_bytes; j++)

        printf(" %02x", fhp->f_handle[j]);

    printf("\n");

    exit(EXIT_SUCCESS);
}
```

### Program source: t_open_by_handle_at.c

```
#define _GNU_SOURCE
#include <err.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Scan /proc/self/mountinfo to find the line whose mount ID matches

   'mount_id'. (An easier way to do this is to install and use the

   'libmount' library provided by the 'util-linux' project.)

   Open the corresponding mount path and return the resulting file

   descriptor. */
static int
open_mount_path_by_id(int mount_id)
{

    int      mi_mount_id, found;

    char     mount_path[PATH_MAX];

    char     *linep;

    FILE     *fp;

    size_t   lsize;

    ssize_t  nread;

    fp = fopen("/proc/self/mountinfo", "r");

    if (fp == NULL)

        err(EXIT_FAILURE, "fopen");

    found = 0;

    linep = NULL;

    while (!found) {

        nread = getline(&linep, &lsize, fp);

        if (nread == -1)

            break;

        nread = sscanf(linep, "%d %*d %*s %*s %s",

                       &mi_mount_id, mount_path);

        if (nread != 2) {

            fprintf(stderr, "Bad sscanf()\n");

            exit(EXIT_FAILURE);

        }

        if (mi_mount_id == mount_id)

            found = 1;

    }

    free(linep);

    fclose(fp);

    if (!found) {

        fprintf(stderr, "Could not find mount point\n");

        exit(EXIT_FAILURE);

    }

    return open(mount_path, O_RDONLY);
}
int
main(int argc, char *argv[])
{

    int                 mount_id, fd, mount_fd, handle_bytes;

    char                buf[1000];
#define LINE_SIZE 100

    char                line1[LINE_SIZE], line2[LINE_SIZE];

    char                *nextp;

    ssize_t             nread;

    struct file_handle  *fhp;

    if ((argc > 1 && strcmp(argv[1], "--help") == 0) || argc > 2) {

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

        exit(EXIT_FAILURE);

    }

    /* Standard input contains mount ID and file handle information:

         Line 1: <mount_id>

         Line 2: <handle_bytes> <handle_type>   <bytes of handle in hex>

    */

    if (fgets(line1, sizeof(line1), stdin) == NULL ||

        fgets(line2, sizeof(line2), stdin) == NULL)

    {

        fprintf(stderr, "Missing mount_id / file handle\n");

        exit(EXIT_FAILURE);

    }

    mount_id = atoi(line1);

    handle_bytes = strtoul(line2, &nextp, 0);

    /* Given handle_bytes, we can now allocate file_handle structure. */

    fhp = malloc(sizeof(*fhp) + handle_bytes);

    if (fhp == NULL)

        err(EXIT_FAILURE, "malloc");

    fhp->handle_bytes = handle_bytes;

    fhp->handle_type = strtoul(nextp, &nextp, 0);

    for (size_t j = 0; j < fhp->handle_bytes; j++)

        fhp->f_handle[j] = strtoul(nextp, &nextp, 16);

    /* Obtain file descriptor for mount point, either by opening

       the pathname specified on the command line, or by scanning

       /proc/self/mounts to find a mount that matches the 'mount_id'

       that we received from stdin. */

    if (argc > 1)

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

    else

        mount_fd = open_mount_path_by_id(mount_id);

    if (mount_fd == -1)

        err(EXIT_FAILURE, "opening mount fd");

    /* Open file using handle and mount point. */

    fd = open_by_handle_at(mount_fd, fhp, O_RDONLY);

    if (fd == -1)

        err(EXIT_FAILURE, "open_by_handle_at");

    /* Try reading a few bytes from the file. */

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

    if (nread == -1)

        err(EXIT_FAILURE, "read");

    printf("Read %zd bytes\n", nread);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
open(2), libblkid(3), blkid(8), findfs(8), mount(8)

The libblkid and libmount documentation in the latest util-linux release at https://www.kernel.org/pub/linux/utils/util-linux/


title: open_how(2type)

summary: how to open a pathname

text:
# open_how(2type)

## NAME
open_how - how to open a pathname

## LIBRARY
Linux kernel headers

## SYNOPSIS

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

```
struct open_how {
    u64  flags;    /* O_* flags */
    u64  mode;     /* Mode for O_{CREAT,TMPFILE} */
    u64  resolve;  /* RESOLVE_* flags */

    /* ... */
};
```

## DESCRIPTION
Specifies how a pathname should be opened.

The fields are as follows:

flags

This field specifies the file creation and file status flags to use when opening the file.

mode

This field specifies the mode for the new file.

resolve

This is a bit mask of flags that modify the way in which all components of a pathname will be resolved (see path_resolution(7) for background information).

## VERSIONS
Extra fields may be appended to the structure, with a zero value in a new field resulting in the kernel behaving as though that extension field was not present. Therefore, a user must zero-fill this structure on initialization.

## STANDARDS
Linux.

## SEE ALSO
openat2(2)