getresuid

title: getresuid(2)

text:
# getresuid(2)

## NAME
getresuid, getresgid - get real, effective, and saved user/group IDs

## SYNOPSIS

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

```
int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
```

## DESCRIPTION
getresuid() returns the real UID, the effective UID, and the saved set-user-ID of the calling process, in the arguments ruid, euid, and suid, respectively. getresgid() performs the analogous task for the process's group IDs.

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

## ERRORS
EFAULT

One of the arguments specified an address outside the calling program's address space.

## VERSIONS
These system calls appeared on Linux starting with kernel 2.1.44.

The prototypes are given by glibc since version 2.3.2, provided _GNU_SOURCE is defined.

## CONFORMING TO
These calls are nonstandard; they also appear on HP-UX and some of the BSDs.

## NOTES
The original Linux getresuid() and getresgid() system calls supported only 16-bit user and group IDs. Subsequently, Linux 2.4 added getresuid32() and getresgid32(), supporting 32-bit IDs. The glibc getresuid() and getresgid() wrapper functions transparently deal with the variations across kernel versions.

## SEE ALSO
getuid(2), setresuid(2), setreuid(2), setuid(2), credentials(7)


getrlimit

package: man-pages

title: getrlimit(2)

summary: get/set resource limits

text:
# getrlimit(2)

## NAME
getrlimit, setrlimit, prlimit - get/set resource limits

## SYNOPSIS

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

```
int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);
```

```
int prlimit(pid_t pid, int resource, const struct rlimit *new_limit,
            struct rlimit *old_limit);
```

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

prlimit():

```
    _GNU_SOURCE
```

## DESCRIPTION
The getrlimit() and setrlimit() system calls get and set resource limits. Each resource has an associated soft and hard limit, as defined by the rlimit structure:

```
struct rlimit {

    rlim_t rlim_cur;  /* Soft limit */

    rlim_t rlim_max;  /* Hard limit (ceiling for rlim_cur) */
};
```

The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit: an unprivileged process may set only its soft limit to a value in the range from 0 up to the hard limit, and (irreversibly) lower its hard limit. A privileged process (under Linux: one with the CAP_SYS_RESOURCE capability in the initial user namespace) may make arbitrary changes to either limit value.

The value RLIM_INFINITY denotes no limit on a resource (both in the structure returned by getrlimit() and in the structure passed to setrlimit()).

The resource argument must be one of:

RLIMIT_AS

This is the maximum size of the process's virtual memory (address space). The limit is specified in bytes, and is rounded down to the system page size. This limit affects calls to brk(2), mmap(2), and mremap(2), which fail with the error ENOMEM upon exceeding this limit. In addition, automatic stack expansion fails (and generates a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)). Since the value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.

RLIMIT_CORE

This is the maximum size of a core file (see core(5)) in bytes that the process may dump. When 0 no core dump files are created. When nonzero, larger dumps are truncated to this size.

RLIMIT_CPU

This is a limit, in seconds, on the amount of CPU time that the process can consume. When the process reaches the soft limit, it is sent a SIGXCPU signal. The default action for this signal is to terminate the process. However, the signal can be caught, and the handler can return control to the main program. If the process continues to consume CPU time, it will be sent SIGXCPU once per second until the hard limit is reached, at which time it is sent SIGKILL. (This latter point describes Linux behavior. Implementations vary in how they treat processes which continue to consume CPU time after reaching the soft limit. Portable applications that need to catch this signal should perform an orderly termination upon first receipt of SIGXCPU.)

RLIMIT_DATA

This is the maximum size of the process's data segment (initialized data, uninitialized data, and heap). The limit is specified in bytes, and is rounded down to the system page size. This limit affects calls to brk(2), sbrk(2), and (since Linux 4.7) mmap(2), which fail with the error ENOMEM upon encountering the soft limit of this resource.

RLIMIT_FSIZE

This is the maximum size in bytes of files that the process may create. Attempts to extend a file beyond this limit result in delivery of a SIGXFSZ signal. By default, this signal terminates a process, but a process can catch this signal instead, in which case the relevant system call (e.g., write(2), truncate(2)) fails with the error EFBIG.

RLIMIT_LOCKS (Linux 2.4.0 to 2.4.24)

This is a limit on the combined number of flock(2) locks and fcntl(2) leases that this process may establish.

RLIMIT_MEMLOCK

This is the maximum number of bytes of memory that may be locked into RAM. This limit is in effect rounded down to the nearest multiple of the system page size. This limit affects mlock(2), mlockall(2), and the mmap(2) MAP_LOCKED operation. Since Linux 2.6.9, it also affects the shmctl(2) SHM_LOCK operation, where it sets a maximum on the total bytes in shared memory segments (see shmget(2)) that may be locked by the real user ID of the calling process. The shmctl(2) SHM_LOCK locks are accounted for separately from the per-process memory locks established by mlock(2), mlockall(2), and mmap(2) MAP_LOCKED; a process can lock bytes up to this limit in each of these two categories.

In Linux kernels before 2.6.9, this limit controlled the amount of memory that could be locked by a privileged process. Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process may lock, and this limit instead governs the amount of memory that an unprivileged process may lock.

RLIMIT_MSGQUEUE (since Linux 2.6.8)

This is a limit on the number of bytes that can be allocated for POSIX message queues for the real user ID of the calling process. This limit is enforced for mq_open(3). Each message queue that the user creates counts (until it is removed) against this limit according to the formula:

Since Linux 3.5:

```
        bytes = attr.mq_maxmsg * sizeof(struct msg_msg) +

                min(attr.mq_maxmsg, MQ_PRIO_MAX) *

                      sizeof(struct posix_msg_tree_node)+

                                /* For overhead */

                attr.mq_maxmsg * attr.mq_msgsize;

                                /* For message data */

```

Linux 3.4 and earlier:

```
        bytes = attr.mq_maxmsg * sizeof(struct msg_msg *) +

                                /* For overhead */

                attr.mq_maxmsg * attr.mq_msgsize;

                                /* For message data */

```

where attr is the mq_attr structure specified as the fourth argument to mq_open(3), and the msg_msg and posix_msg_tree_node structures are kernel-internal structures.

The "overhead" addend in the formula accounts for overhead bytes required by the implementation and ensures that the user cannot create an unlimited number of zero-length messages (such messages nevertheless each consume some system memory for bookkeeping overhead).

RLIMIT_NICE (since Linux 2.6.12, but see BUGS below)

This specifies a ceiling to which the process's nice value can be raised using setpriority(2) or nice(2). The actual ceiling for the nice value is calculated as 20 - rlim_cur. The useful range for this limit is thus from 1 (corresponding to a nice value of 19) to 40 (corresponding to a nice value of -20). This unusual choice of range was necessary because negative numbers cannot be specified as resource limit values, since they typically have special meanings. For example, RLIM_INFINITY typically is the same as -1. For more detail on the nice value, see sched(7).

RLIMIT_NOFILE

This specifies a value one greater than the maximum file descriptor number that can be opened by this process. Attempts (open(2), pipe(2), dup(2), etc.) to exceed this limit yield the error EMFILE. (Historically, this limit was named RLIMIT_OFILE on BSD.)

Since Linux 4.5, this limit also defines the maximum number of file descriptors that an unprivileged process (one without the CAP_SYS_RESOURCE capability) may have "in flight" to other processes, by being passed across UNIX domain sockets. This limit applies to the sendmsg(2) system call. For further details, see unix(7).

RLIMIT_NPROC

This is a limit on the number of extant process (or, more precisely on Linux, threads) for the real user ID of the calling process. So long as the current number of processes belonging to this process's real user ID is greater than or equal to this limit, fork(2) fails with the error EAGAIN.

The RLIMIT_NPROC limit is not enforced for processes that have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.

RLIMIT_RSS

This is a limit (in bytes) on the process's resident set (the number of virtual pages resident in RAM). This limit has effect only in Linux 2.4.x, x < 30, and there affects only calls to madvise(2) specifying MADV_WILLNEED.

RLIMIT_RTPRIO (since Linux 2.6.12, but see BUGS)

This specifies a ceiling on the real-time priority that may be set for this process using sched_setscheduler(2) and sched_setparam(2).

For further details on real-time scheduling policies, see sched(7)

RLIMIT_RTTIME (since Linux 2.6.25)

This is a limit (in microseconds) on the amount of CPU time that a process scheduled under a real-time scheduling policy may consume without making a blocking system call. For the purpose of this limit, each time a process makes a blocking system call, the count of its consumed CPU time is reset to zero. The CPU time count is not reset if the process continues trying to use the CPU but is preempted, its time slice expires, or it calls sched_yield(2).

Upon reaching the soft limit, the process is sent a SIGXCPU signal. If the process catches or ignores this signal and continues consuming CPU time, then SIGXCPU will be generated once each second until the hard limit is reached, at which point the process is sent a SIGKILL signal.

The intended use of this limit is to stop a runaway real-time process from locking up the system.

For further details on real-time scheduling policies, see sched(7)

RLIMIT_SIGPENDING (since Linux 2.6.8)

This is a limit on the number of signals that may be queued for the real user ID of the calling process. Both standard and real-time signals are counted for the purpose of checking this limit. However, the limit is enforced only for sigqueue(3); it is always possible to use kill(2) to queue one instance of any of the signals that are not already queued to the process.

RLIMIT_STACK

This is the maximum size of the process stack, in bytes. Upon reaching this limit, a SIGSEGV signal is generated. To handle this signal, a process must employ an alternate signal stack (sigaltstack(2)).

Since Linux 2.6.23, this limit also determines the amount of space used for the process's command-line arguments and environment variables; for details, see execve(2).

### prlimit()
The Linux-specific prlimit() system call combines and extends the functionality of setrlimit() and getrlimit(). It can be used to both set and get the resource limits of an arbitrary process.

The resource argument has the same meaning as for setrlimit() and getrlimit().

If the new_limit argument is a not NULL, then the rlimit structure to which it points is used to set new values for the soft and hard limits for resource. If the old_limit argument is a not NULL, then a successful call to prlimit() places the previous soft and hard limits for resource in the rlimit structure pointed to by old_limit.

The pid argument specifies the ID of the process on which the call is to operate. If pid is 0, then the call applies to the calling process. To set or get the resources of a process other than itself, the caller must have the CAP_SYS_RESOURCE capability in the user namespace of the process whose resource limits are being changed, or the real, effective, and saved set user IDs of the target process must match the real user ID of the caller and the real, effective, and saved set group IDs of the target process must match the real group ID of the caller.

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

## ERRORS
EFAULT

A pointer argument points to a location outside the accessible address space.

EINVAL

The value specified in resource is not valid; or, for setrlimit() or prlimit(): rlim->rlim_cur was greater than rlim->rlim_max.

EPERM

An unprivileged process tried to raise the hard limit; the CAP_SYS_RESOURCE capability is required to do this.

EPERM

The caller tried to increase the hard RLIMIT_NOFILE limit above the maximum defined by /proc/sys/fs/nr_open (see proc(5))

EPERM

(prlimit()) The calling process did not have permission to set limits for the process specified by pid.

ESRCH

Could not find a process with the ID specified in pid.

## VERSIONS
The prlimit() system call is available since Linux 2.6.36. Library support is available since glibc 2.13.

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

Interface

Attribute

Value

getrlimit (), setrlimit (), prlimit ()

Thread safety

MT-Safe

## CONFORMING TO
getrlimit(), setrlimit(): POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.

prlimit(): Linux-specific.

RLIMIT_MEMLOCK and RLIMIT_NPROC derive from BSD and are not specified in POSIX.1; they are present on the BSDs and Linux, but on few other implementations. RLIMIT_RSS derives from BSD and is not specified in POSIX.1; it is nevertheless present on most implementations. RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_RTTIME, and RLIMIT_SIGPENDING are Linux-specific.

## NOTES
A child process created via fork(2) inherits its parent's resource limits. Resource limits are preserved across execve(2).

Resource limits are per-process attributes that are shared by all of the threads in a process.

Lowering the soft limit for a resource below the process's current consumption of that resource will succeed (but will prevent the process from further increasing its consumption of the resource).

One can set the resource limits of the shell using the built-in ulimit command (limit in csh(1)). The shell's resource limits are inherited by the processes that it creates to execute commands.

Since Linux 2.6.24, the resource limits of any process can be inspected via /proc/[pid]/limits; see proc(5).

Ancient systems provided a vlimit() function with a similar purpose to setrlimit(). For backward compatibility, glibc also provides vlimit(). All new applications should be written using setrlimit().

### C library/kernel ABI differences
Since version 2.13, the glibc getrlimit() and setrlimit() wrapper functions no longer invoke the corresponding system calls, but instead employ prlimit(), for the reasons described in BUGS.

The name of the glibc wrapper function is prlimit(); the underlying system call is prlimit64().

## BUGS
In older Linux kernels, the SIGXCPU and SIGKILL signals delivered when a process encountered the soft and hard RLIMIT_CPU limits were delivered one (CPU) second later than they should have been. This was fixed in kernel 2.6.8.

In 2.6.x kernels before 2.6.17, a RLIMIT_CPU limit of 0 is wrongly treated as "no limit" (like RLIM_INFINITY). Since Linux 2.6.17, setting a limit of 0 does have an effect, but is actually treated as a limit of 1 second.

A kernel bug means that RLIMIT_RTPRIO does not work in kernel 2.6.12; the problem is fixed in kernel 2.6.13.

In kernel 2.6.12, there was an off-by-one mismatch between the priority ranges returned by getpriority(2) and RLIMIT_NICE. This had the effect that the actual ceiling for the nice value was calculated as 19 - rlim_cur. This was fixed in kernel 2.6.13.

Since Linux 2.6.12, if a process reaches its soft RLIMIT_CPU limit and has a handler installed for SIGXCPU, then, in addition to invoking the signal handler, the kernel increases the soft limit by one second. This behavior repeats if the process continues to consume CPU time, until the hard limit is reached, at which point the process is killed. Other implementations do not change the RLIMIT_CPU soft limit in this manner, and the Linux behavior is probably not standards conformant; portable applications should avoid relying on this Linux-specific behavior. The Linux-specific RLIMIT_RTTIME limit exhibits the same behavior when the soft limit is encountered.

Kernels before 2.4.22 did not diagnose the error EINVAL for setrlimit() when rlim->rlim_cur was greater than rlim->rlim_max.

Linux doesn't return an error when an attempt to set RLIMIT_CPU has failed, for compatibility reasons.

### Representation of "large" resource limit values on 32-bit platforms
The glibc getrlimit() and setrlimit() wrapper functions use a 64-bit rlim_t data type, even on 32-bit platforms. However, the rlim_t data type used in the getrlimit() and setrlimit() system calls is a (32-bit) unsigned long. Furthermore, in Linux, the kernel represents resource limits on 32-bit platforms as unsigned long. However, a 32-bit data type is not wide enough. The most pertinent limit here is RLIMIT_FSIZE, which specifies the maximum size to which a file can grow: to be useful, this limit must be represented using a type that is as wide as the type used to represent file offsets—that is, as wide as a 64-bit off_t (assuming a program compiled with _FILE_OFFSET_BITS=64).

To work around this kernel limitation, if a program tried to set a resource limit to a value larger than can be represented in a 32-bit unsigned long, then the glibc setrlimit() wrapper function silently converted the limit value to RLIM_INFINITY. In other words, the requested resource limit setting was silently ignored.

Since version 2.13, glibc works around the limitations of the getrlimit() and setrlimit() system calls by implementing setrlimit() and getrlimit() as wrapper functions that call prlimit().

## EXAMPLES
The program below demonstrates the use of prlimit().

```
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/resource.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \

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

    struct rlimit old, new;

    struct rlimit *newp;

    pid_t pid;

    if (!(argc == 2 || argc == 4)) {

        fprintf(stderr, "Usage: %s <pid> [<new-soft-limit> "

                "<new-hard-limit>]\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    pid = atoi(argv[1]);        /* PID of target process */

    newp = NULL;

    if (argc == 4) {

        new.rlim_cur = atoi(argv[2]);

        new.rlim_max = atoi(argv[3]);

        newp = &new;

    }

    /* Set CPU time limit of target process; retrieve and display

       previous limit */

    if (prlimit(pid, RLIMIT_CPU, newp, &old) == -1)

        errExit("prlimit-1");

    printf("Previous limits: soft=%jd; hard=%jd\n",

            (intmax_t) old.rlim_cur, (intmax_t) old.rlim_max);

    /* Retrieve and display new CPU time limit */

    if (prlimit(pid, RLIMIT_CPU, NULL, &old) == -1)

        errExit("prlimit-2");

    printf("New limits: soft=%jd; hard=%jd\n",

            (intmax_t) old.rlim_cur, (intmax_t) old.rlim_max);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
prlimit(1), dup(2), fcntl(2), fork(2), getrusage(2), mlock(2), mmap(2), open(2), quotactl(2), sbrk(2), shmctl(2), malloc(3), sigqueue(3), ulimit(3), core(5), capabilities(7), cgroups(7), credentials(7), signal(7)


getrusage

title: getrusage(2)

summary: get resource usage

text:
# getrusage(2)

## NAME
getrusage - get resource usage

## SYNOPSIS

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

```
int getrusage(int who, struct rusage *usage);
```

## DESCRIPTION
getrusage() returns resource usage measures for who, which can be one of the following:

RUSAGE_SELF

Return resource usage statistics for the calling process, which is the sum of resources used by all threads in the process.

RUSAGE_CHILDREN

Return resource usage statistics for all children of the calling process that have terminated and been waited for. These statistics will include the resources used by grandchildren, and further removed descendants, if all of the intervening descendants waited on their terminated children.

RUSAGE_THREAD (since Linux 2.6.26)

Return resource usage statistics for the calling thread. The _GNU_SOURCE feature test macro must be defined (before including any header file) in order to obtain the definition of this constant from <sys/resource.h>.

The resource usages are returned in the structure pointed to by usage, which has the following form:

```
struct rusage {

    struct timeval ru_utime; /* user CPU time used */

    struct timeval ru_stime; /* system CPU time used */

    long   ru_maxrss;        /* maximum resident set size */

    long   ru_ixrss;         /* integral shared memory size */

    long   ru_idrss;         /* integral unshared data size */

    long   ru_isrss;         /* integral unshared stack size */

    long   ru_minflt;        /* page reclaims (soft page faults) */

    long   ru_majflt;        /* page faults (hard page faults) */

    long   ru_nswap;         /* swaps */

    long   ru_inblock;       /* block input operations */

    long   ru_oublock;       /* block output operations */

    long   ru_msgsnd;        /* IPC messages sent */

    long   ru_msgrcv;        /* IPC messages received */

    long   ru_nsignals;      /* signals received */

    long   ru_nvcsw;         /* voluntary context switches */

    long   ru_nivcsw;        /* involuntary context switches */
};
```

Not all fields are completed; unmaintained fields are set to zero by the kernel. (The unmaintained fields are provided for compatibility with other systems, and because they may one day be supported on Linux.) The fields are interpreted as follows:

ru_utime

This is the total amount of time spent executing in user mode, expressed in a timeval structure (seconds plus microseconds).

ru_stime

This is the total amount of time spent executing in kernel mode, expressed in a timeval structure (seconds plus microseconds).

ru_maxrss (since Linux 2.6.32)

This is the maximum resident set size used (in kilobytes). For RUSAGE_CHILDREN, this is the resident set size of the largest child, not the maximum resident set size of the process tree.

ru_ixrss (unmaintained)

This field is currently unused on Linux.

ru_idrss (unmaintained)

This field is currently unused on Linux.

ru_isrss (unmaintained)

This field is currently unused on Linux.

ru_minflt

The number of page faults serviced without any I/O activity; here I/O activity is avoided by “reclaiming” a page frame from the list of pages awaiting reallocation.

ru_majflt

The number of page faults serviced that required I/O activity.

ru_nswap (unmaintained)

This field is currently unused on Linux.

ru_inblock (since Linux 2.6.22)

The number of times the filesystem had to perform input.

ru_oublock (since Linux 2.6.22)

The number of times the filesystem had to perform output.

ru_msgsnd (unmaintained)

This field is currently unused on Linux.

ru_msgrcv (unmaintained)

This field is currently unused on Linux.

ru_nsignals (unmaintained)

This field is currently unused on Linux.

ru_nvcsw (since Linux 2.6)

The number of times a context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource).

ru_nivcsw (since Linux 2.6)

The number of times a context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice.

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

## ERRORS
EFAULT

usage points outside the accessible address space.

EINVAL

who is invalid.

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

Interface

Attribute

Value

getrusage ()

Thread safety

MT-Safe

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. POSIX.1 specifies getrusage(), but specifies only the fields ru_utime and ru_stime.

RUSAGE_THREAD is Linux-specific.

## NOTES
Resource usage metrics are preserved across an execve(2).

In Linux kernel versions before 2.6.9, if the disposition of SIGCHLD is set to SIG_IGN then the resource usages of child processes are automatically included in the value returned by RUSAGE_CHILDREN, although POSIX.1-2001 explicitly prohibits this. This nonconformance is rectified in Linux 2.6.9 and later.

The structure definition shown at the start of this page was taken from 4.3BSD Reno.

Ancient systems provided a vtimes() function with a similar purpose to getrusage(). For backward compatibility, glibc (up until version 2.32) also provides vtimes(). All new applications should be written using getrusage(). (Since version 2.33, glibc no longer provides an vtimes() implementation.)

See also the description of /proc/[pid]/stat in proc(5).

## SEE ALSO
clock_gettime(2), getrlimit(2), times(2), wait(2), wait4(2), clock(3)


getsid

title: getsid(2)

summary: get session ID

text:
# getsid(2)

## NAME
getsid - get session ID

## SYNOPSIS

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

```
pid_t getsid(pid_t pid);
```

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

getsid():

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
```

## DESCRIPTION
getsid(0) returns the session ID of the calling process. getsid() returns the session ID of the process with process ID pid. If pid is 0, getsid() returns the session ID of the calling process.

## RETURN VALUE
On success, a session ID is returned. On error, (pid_t) -1 is returned, and errno is set to indicate the error.

## ERRORS
EPERM

A process with process ID pid exists, but it is not in the same session as the calling process, and the implementation considers this an error.

ESRCH

No process with process ID pid was found.

## VERSIONS
This system call is available on Linux since version 2.0.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4.

## NOTES
Linux does not return EPERM.

See credentials(7) for a description of sessions and session IDs.

## SEE ALSO
getpgid(2), setsid(2), credentials(7)


getsockname

title: getsockname(2)

summary: get socket name

text:
# getsockname(2)

## NAME
getsockname - get socket name

## SYNOPSIS

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

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

## DESCRIPTION
getsockname() returns the current address to which the socket sockfd is bound, in the buffer pointed to by addr. The addrlen argument should be initialized to indicate the amount of space (in bytes) pointed to by addr. On return it contains the actual size of the socket address.

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

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

## ERRORS
EBADF

The argument sockfd is not a valid file descriptor.

EFAULT

The addr argument points to memory not in a valid part of the process address space.

EINVAL

addrlen is invalid (e.g., is negative).

ENOBUFS

Insufficient resources were available in the system to perform the operation.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD (getsockname() first appeared in 4.2BSD).

## NOTES
For background on the socklen_t type, see accept(2).

## SEE ALSO
bind(2), socket(2), getifaddrs(3), ip(7), socket(7), unix(7)


getsockopt

title: getsockopt(2)

summary: get and set options on sockets

text:
# getsockopt(2)

## NAME
getsockopt, setsockopt - get and set options on sockets

## SYNOPSIS

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

```
int getsockopt(int sockfd, int level, int optname,
               void *restrict optval, socklen_t *restrict optlen);
int setsockopt(int sockfd, int level, int optname,
               const void *optval, socklen_t optlen);
```

## DESCRIPTION
getsockopt() and setsockopt() manipulate options for the socket referred to by the file descriptor sockfd. Options may exist at multiple protocol levels; they are always present at the uppermost socket level.

When manipulating socket options, the level at which the option resides and the name of the option must be specified. To manipulate options at the sockets API level, level is specified as SOL_SOCKET. To manipulate options at any other level the protocol number of the appropriate protocol controlling the option is supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, level should be set to the protocol number of TCP; see getprotoent(3).

The arguments optval and optlen are used to access option values for setsockopt(). For getsockopt() they identify a buffer in which the value for the requested option(s) are to be returned. For getsockopt(), optlen is a value-result argument, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned. If no option value is to be supplied or returned, optval may be NULL.

Optname and any specified options are passed uninterpreted to the appropriate protocol module for interpretation. The include file <sys/socket.h> contains definitions for socket level options, described below. Options at other protocol levels vary in format and name; consult the appropriate entries in section 4 of the manual.

Most socket-level options utilize an int argument for optval. For setsockopt(), the argument should be nonzero to enable a boolean option, or zero if the option is to be disabled.

For a description of the available socket options see socket(7) and the appropriate protocol man pages.

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

Netfilter allows the programmer to define custom socket options with associated handlers; for such options, the return value on success is the value returned by the handler.

## ERRORS
EBADF

The argument sockfd is not a valid file descriptor.

EFAULT

The address pointed to by optval is not in a valid part of the process address space. For getsockopt(), this error may also be returned if optlen is not in a valid part of the process address space.

EINVAL

optlen invalid in setsockopt(). In some cases this error can also occur for an invalid value in optval (e.g., for the IP_ADD_MEMBERSHIP option described in ip(7)).

ENOPROTOOPT

The option is unknown at the level indicated.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD (these system calls first appeared in 4.2BSD).

## NOTES
For background on the socklen_t type, see accept(2).

## BUGS
Several of the socket options should be handled at lower levels of the system.

## SEE ALSO
ioctl(2), socket(2), getprotoent(3), protocols(5), ip(7), packet(7), socket(7), tcp(7), udp(7), unix(7)


gettid

title: gettid(2)

summary: get thread identification

text:
# gettid(2)

## NAME
gettid - get thread identification

## SYNOPSIS

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

```
pid_t gettid(void);
```

## DESCRIPTION
gettid() returns the caller's thread ID (TID). In a single-threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one has a unique TID. For further details, see the discussion of CLONE_THREAD in clone(2).

## RETURN VALUE
On success, returns the thread ID of the calling thread.

## ERRORS
This call is always successful.

## VERSIONS
The gettid() system call first appeared on Linux in kernel 2.4.11. Library support was added in glibc 2.30. (Earlier glibc versions did not provide a wrapper for this system call, necessitating the use of syscall(2).)

## CONFORMING TO
gettid() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
The thread ID returned by this call is not the same thing as a POSIX thread ID (i.e., the opaque value returned by pthread_self(3)).

In a new thread group created by a clone(2) call that does not specify the CLONE_THREAD flag (or, equivalently, a new process created by fork(2)), the new process is a thread group leader, and its thread group ID (the value returned by getpid(2)) is the same as its thread ID (the value returned by gettid()).

## SEE ALSO
capget(2), clone(2), fcntl(2), fork(2), get_robust_list(2), getpid(2), ioprio_set(2), perf_event_open(2), sched_setaffinity(2), sched_setparam(2), sched_setscheduler(2), tgkill(2), timer_create(2)


gettimeofday

title: gettimeofday(2)

summary: get / set time

text:
# gettimeofday(2)

## NAME
gettimeofday, settimeofday - get / set time

## SYNOPSIS

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

```
int gettimeofday(struct timeval *restrict tv,
                 struct timezone *restrict tz);
int settimeofday(const struct timeval *tv,
                 const struct timezone *tz);
```

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

settimeofday():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    Glibc 2.19 and earlier:

        _BSD_SOURCE
```

## DESCRIPTION
The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone.

The tv argument is a struct timeval (as specified in <sys/time.h>):

```
struct timeval {

    time_t      tv_sec;     /* seconds */

    suseconds_t tv_usec;    /* microseconds */
};
```

and gives the number of seconds and microseconds since the Epoch (see time(2)).

The tz argument is a struct timezone:

```
struct timezone {

    int tz_minuteswest;     /* minutes west of Greenwich */

    int tz_dsttime;         /* type of DST correction */
};
```

If either tv or tz is NULL, the corresponding structure is not set or returned. (However, compilation warnings will result if tv is NULL.)

The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL. (See NOTES below.)

Under Linux, there are some peculiar "warp clock" semantics associated with the settimeofday() system call if on the very first call (after booting) that has a non-NULL tz argument, the tv argument is NULL and the tz_minuteswest field is nonzero. (The tz_dsttime field should be zero for this case.) In such a case it is assumed that the CMOS clock is on local time, and that it has to be incremented by this amount to get UTC system time. No doubt it is a bad idea to use this feature.

## RETURN VALUE
gettimeofday() and settimeofday() return 0 for success. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EFAULT

One of tv or tz pointed outside the accessible address space.

EINVAL

(settimeofday()): timezone is invalid.

EINVAL

(settimeofday()): tv.tv_sec is negative or tv.tv_usec is outside the range [0..999,999].

EINVAL (since Linux 4.3)

(settimeofday()): An attempt was made to set the time to a value less than the current value of the CLOCK_MONOTONIC clock (see clock_gettime(2)).

EPERM

The calling process has insufficient privilege to call settimeofday(); under Linux the CAP_SYS_TIME capability is required.

## CONFORMING TO
SVr4, 4.3BSD. POSIX.1-2001 describes gettimeofday() but not settimeofday(). POSIX.1-2008 marks gettimeofday() as obsolete, recommending the use of clock_gettime(2) instead.

## NOTES
The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

Macros for operating on timeval structures are described in timeradd(3).

Traditionally, the fields of struct timeval were of type long.

### C library/kernel differences
On some architectures, an implementation of gettimeofday() is provided in the vdso(7).

### The tz_dsttime field
On a non-Linux kernel, with glibc, the tz_dsttime field of struct timezone will be set to a nonzero value by gettimeofday() if the current timezone has ever had or will have a daylight saving rule applied. In this sense it exactly mirrors the meaning of daylight(3) for the current zone. On Linux, with glibc, the setting of the tz_dsttime field of struct timezone has never been used by settimeofday() or gettimeofday(). Thus, the following is purely of historical interest.

On old systems, the field tz_dsttime contains a symbolic constant (values are given below) that indicates in which part of the year Daylight Saving Time is in force. (Note: this value is constant throughout the year: it does not indicate that DST is in force, it just selects an algorithm.) The daylight saving time algorithms defined are as follows:

```
DST_NONE     /* not on DST */
DST_USA      /* USA style DST */
DST_AUST     /* Australian style DST */
DST_WET      /* Western European DST */
DST_MET      /* Middle European DST */
DST_EET      /* Eastern European DST */
DST_CAN      /* Canada */
DST_GB       /* Great Britain and Eire */
DST_RUM      /* Romania */
DST_TUR      /* Turkey */
DST_AUSTALT  /* Australian style with shift in 1986 */
```

Of course it turned out that the period in which Daylight Saving Time is in force cannot be given by a simple algorithm, one per country; indeed, this period is determined by unpredictable political decisions. So this method of representing timezones has been abandoned.

## SEE ALSO
date(1), adjtimex(2), clock_gettime(2), time(2), ctime(3), ftime(3), timeradd(3), capabilities(7), time(7), vdso(7), hwclock(8)


getuid

title: getuid(2)

summary: get user identity

text:
# getuid(2)

## NAME
getuid, geteuid - get user identity

## SYNOPSIS

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

```
uid_t getuid(void);
uid_t geteuid(void);
```

## DESCRIPTION
getuid() returns the real user ID of the calling process.

geteuid() returns the effective user ID of the calling process.

## ERRORS
These functions are always successful and never modify errno.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.3BSD.

## NOTES

### History
In UNIX V6 the getuid() call returned (euid << 8) + uid. UNIX V7 introduced separate calls getuid() and geteuid().

The original Linux getuid() and geteuid() system calls supported only 16-bit user IDs. Subsequently, Linux 2.4 added getuid32() and geteuid32(), supporting 32-bit IDs. The glibc getuid() and geteuid() wrapper functions transparently deal with the variations across kernel versions.

On Alpha, instead of a pair of getuid() and geteuid() system calls, a single getxuid() system call is provided, which returns a pair of real and effective UIDs. The glibc getuid() and geteuid() wrapper functions transparently deal with this. See syscall(2) for details regarding register mapping.

## SEE ALSO
getresuid(2), setreuid(2), setuid(2), credentials(7)


getunwind

title: getunwind(2)

summary: copy the unwind data to caller's buffer

text:
# getunwind(2)

## NAME
getunwind - copy the unwind data to caller's buffer

## SYNOPSIS

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

```
long syscall(SYS_getunwind, void *buf, size_t buf_size);
```

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

## DESCRIPTION
Note: this system call is obsolete.

The IA-64-specific getunwind() system call copies the kernel's call frame unwind data into the buffer pointed to by buf and returns the size of the unwind data; this data describes the gate page (kernel code that is mapped into user space).

The size of the buffer buf is specified in buf_size. The data is copied only if buf_size is greater than or equal to the size of the unwind data and buf is not NULL; otherwise, no data is copied, and the call succeeds, returning the size that would be needed to store the unwind data.

The first part of the unwind data contains an unwind table. The rest contains the associated unwind information, in no particular order. The unwind table contains entries of the following form:

```
u64 start;      (64-bit address of start of function)
u64 end;        (64-bit address of end of function)
u64 info;       (BUF-relative offset to unwind info)
```

An entry whose start value is zero indicates the end of the table. For more information about the format, see the IA-64 Software Conventions and Runtime Architecture manual.

## RETURN VALUE
On success, getunwind() returns the size of the unwind data. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
getunwind() fails with the error EFAULT if the unwind info can't be stored in the space specified by buf.

## VERSIONS
This system call is available since Linux 2.4.

## CONFORMING TO
This system call is Linux-specific, and is available only on the IA-64 architecture.

## NOTES
This system call has been deprecated. The modern way to obtain the kernel's unwind data is via the vdso(7).

## SEE ALSO
getauxval(3)


getxattr

title: getxattr(2)

summary: retrieve an extended attribute value

text:
# getxattr(2)

## NAME
getxattr, lgetxattr, fgetxattr - retrieve an extended attribute value

## SYNOPSIS

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

```
ssize_t getxattr(const char *path, const char *name,
                 void *value, size_t size);
ssize_t lgetxattr(const char *path, const char *name,
                 void *value, size_t size);
ssize_t fgetxattr(int fd, const char *name,
                 void *value, size_t size);
```

## DESCRIPTION
Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc.). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in xattr(7).

getxattr() retrieves the value of the extended attribute identified by name and associated with the given path in the filesystem. The attribute value is placed in the buffer pointed to by value; size specifies the size of that buffer. The return value of the call is the number of bytes placed in value.

lgetxattr() is identical to getxattr(), except in the case of a symbolic link, where the link itself is interrogated, not the file that it refers to.

fgetxattr() is identical to getxattr(), only the open file referred to by fd (as returned by open(2)) is interrogated in place of path.

An extended attribute name is a null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode. The value of an extended attribute is a chunk of arbitrary textual or binary data that was assigned using setxattr(2).

If size is specified as zero, these calls return the current size of the named extended attribute (and leave value unchanged). This can be used to determine the size of the buffer that should be supplied in a subsequent call. (But, bear in mind that there is a possibility that the attribute value may change between the two calls, so that it is still necessary to check the return status from the second call.)

## RETURN VALUE
On success, these calls return a nonnegative value which is the size (in bytes) of the extended attribute value. On failure, -1 is returned and errno is set to indicate the error.

## ERRORS
E2BIG

The size of the attribute value is larger than the maximum size allowed; the attribute cannot be retrieved. This can happen on filesystems that support very large attribute values such as NFSv4, for example.

ENODATA

The named attribute does not exist, or the process has no access to this attribute.

ENOTSUP

Extended attributes are not supported by the filesystem, or are disabled.

ERANGE

The size of the value buffer is too small to hold the result.

In addition, the errors documented in stat(2) can also occur.

## VERSIONS
These system calls have been available on Linux since kernel 2.4; glibc support is provided since version 2.3.

## CONFORMING TO
These system calls are Linux-specific.

## EXAMPLES
See listxattr(2).

## SEE ALSO
getfattr(1), setfattr(1), listxattr(2), open(2), removexattr(2), setxattr(2), stat(2), symlink(7), xattr(7)


idle

title: idle(2)

summary: make process 0 idle

text:
# idle(2)

## NAME
idle - make process 0 idle

## SYNOPSIS

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

```
int idle(void);
```

## DESCRIPTION
idle() is an internal system call used during bootstrap. It marks the process's pages as swappable, lowers its priority, and enters the main scheduling loop. idle() never returns.

Only process 0 may call idle(). Any user process, even a process with superuser permission, will receive EPERM.

## RETURN VALUE
idle() never returns for process 0, and always returns -1 for a user process.

## ERRORS
EPERM

Always, for a user process.

## VERSIONS
Since Linux 2.3.13, this system call does not exist anymore.

## CONFORMING TO
This function is Linux-specific, and should not be used in programs intended to be portable.


title: init_module(2)

summary: load a kernel module

text:
# init_module(2)

## NAME
init_module, finit_module - load a kernel module

## SYNOPSIS

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

```
int syscall(SYS_init_module, void *module_image, unsigned long len,
            const char *param_values);
int syscall(SYS_finit_module, int fd, const char *param_values,
            int flags);
```

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

## DESCRIPTION
init_module() loads an ELF image into kernel space, performs any necessary symbol relocations, initializes module parameters to values provided by the caller, and then runs the module's init function. This system call requires privilege.

The module_image argument points to a buffer containing the binary image to be loaded; len specifies the size of that buffer. The module image should be a valid ELF image, built for the running kernel.

The param_values argument is a string containing space-delimited specifications of the values for module parameters (defined inside the module using module_param() and module_param_array()). The kernel parses this string and initializes the specified parameters. Each of the parameter specifications has the form:

name[=value[,value...]]

The parameter name is one of those defined within the module using module_param() (see the Linux kernel source file include/linux/moduleparam.h). The parameter value is optional in the case of bool and invbool parameters. Values for array parameters are specified as a comma-separated list.

### finit_module()
The finit_module() system call is like init_module(), but reads the module to be loaded from the file descriptor fd. It is useful when the authenticity of a kernel module can be determined from its location in the filesystem; in cases where that is possible, the overhead of using cryptographically signed modules to determine the authenticity of a module can be avoided. The param_values argument is as for init_module().

The flags argument modifies the operation of finit_module(). It is a bit mask value created by ORing together zero or more of the following flags:

MODULE_INIT_IGNORE_MODVERSIONS

Ignore symbol version hashes.

MODULE_INIT_IGNORE_VERMAGIC

Ignore kernel version magic.

There are some safety checks built into a module to ensure that it matches the kernel against which it is loaded. These checks are recorded when the module is built and verified when the module is loaded. First, the module records a "vermagic" string containing the kernel version number and prominent features (such as the CPU type). Second, if the module was built with the CONFIG_MODVERSIONS configuration option enabled, a version hash is recorded for each symbol the module uses. This hash is based on the types of the arguments and return value for the function named by the symbol. In this case, the kernel version number within the "vermagic" string is ignored, as the symbol version hashes are assumed to be sufficiently reliable.

Using the MODULE_INIT_IGNORE_VERMAGIC flag indicates that the "vermagic" string is to be ignored, and the MODULE_INIT_IGNORE_MODVERSIONS flag indicates that the symbol version hashes are to be ignored. If the kernel is built to permit forced loading (i.e., configured with CONFIG_MODULE_FORCE_LOAD), then loading continues, otherwise it fails with the error ENOEXEC as expected for malformed modules.

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

## ERRORS
EBADMSG (since Linux 3.7)

Module signature is misformatted.

EBUSY

Timeout while trying to resolve a symbol reference by this module.

EFAULT

An address argument referred to a location that is outside the process's accessible address space.

ENOKEY (since Linux 3.7)

Module signature is invalid or the kernel does not have a key for this module. This error is returned only if the kernel was configured with CONFIG_MODULE_SIG_FORCE; if the kernel was not configured with this option, then an invalid or unsigned module simply taints the kernel.

ENOMEM

Out of memory.

EPERM

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

The following errors may additionally occur for init_module():

EEXIST

A module with this name is already loaded.

EINVAL

param_values is invalid, or some part of the ELF image in module_image contains inconsistencies.

ENOEXEC

The binary image supplied in module_image is not an ELF image, or is an ELF image that is invalid or for a different architecture.

The following errors may additionally occur for finit_module():

EBADF

The file referred to by fd is not opened for reading.

EFBIG

The file referred to by fd is too large.

EINVAL

flags is invalid.

ENOEXEC

fd does not refer to an open file.

In addition to the above errors, if the module's init function is executed and returns an error, then init_module() or finit_module() fails and errno is set to the value returned by the init function.

## VERSIONS
finit_module() is available since Linux 3.8.

## CONFORMING TO
init_module() and finit_module() are Linux-specific.

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

Information about currently loaded modules can be found in /proc/modules and in the file trees under the per-module subdirectories under /sys/module.

See the Linux kernel source file include/linux/module.h for some useful background information.

### Linux 2.4 and earlier
In Linux 2.4 and earlier, the init_module() system call was rather different:

\#include <linux/module.h>

int init_module(const char *name, struct module *image);

(User-space applications can detect which version of init_module() is available by calling query_module(); the latter call fails with the error ENOSYS on Linux 2.6 and later.)

The older version of the system call loads the relocated module image pointed to by image into kernel space and runs the module's init function. The caller is responsible for providing the relocated image (since Linux 2.6, the init_module() system call does the relocation).

The module image begins with a module structure and is followed by code and data as appropriate. Since Linux 2.2, the module structure is defined as follows:

```
struct module {

    unsigned long         size_of_struct;

    struct module        *next;

    const char           *name;

    unsigned long         size;

    long                  usecount;

    unsigned long         flags;

    unsigned int          nsyms;

    unsigned int          ndeps;

    struct module_symbol *syms;

    struct module_ref    *deps;

    struct module_ref    *refs;

    int                 (*init)(void);

    void                (*cleanup)(void);

    const struct exception_table_entry *ex_table_start;

    const struct exception_table_entry *ex_table_end;
#ifdef __alpha__

    unsigned long gp;
#endif
};
```

All of the pointer fields, with the exception of next and refs, are expected to point within the module body and be initialized as appropriate for kernel space, that is, relocated with the rest of the module.

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


title: inotify_add_watch(2)

text:
# inotify_add_watch(2)

## NAME
inotify_add_watch - add a watch to an initialized inotify instance

## SYNOPSIS

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

```
int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
```

## DESCRIPTION
inotify_add_watch() adds a new watch, or modifies an existing watch, for the file whose location is specified in pathname; the caller must have read permission for this file. The fd argument is a file descriptor referring to the inotify instance whose watch list is to be modified. The events to be monitored for pathname are specified in the mask bit-mask argument. See inotify(7) for a description of the bits that can be set in mask.

A successful call to inotify_add_watch() returns a unique watch descriptor for this inotify instance, for the filesystem object (inode) that corresponds to pathname. If the filesystem object was not previously being watched by this inotify instance, then the watch descriptor is newly allocated. If the filesystem object was already being watched (perhaps via a different link to the same object), then the descriptor for the existing watch is returned.

The watch descriptor is returned by later read(2)s from the inotify file descriptor. These reads fetch inotify_event structures (see inotify(7)) indicating filesystem events; the watch descriptor inside this structure identifies the object for which the event occurred.

## RETURN VALUE
On success, inotify_add_watch() returns a watch descriptor (a nonnegative integer). On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

Read access to the given file is not permitted.

EBADF

The given file descriptor is not valid.

EEXIST

mask contains IN_MASK_CREATE and pathname refers to a file already being watched by the same fd.

EFAULT

pathname points outside of the process's accessible address space.

EINVAL

The given event mask contains no valid events; or mask contains both IN_MASK_ADD and IN_MASK_CREATE; or fd is not an inotify file descriptor.

ENAMETOOLONG

pathname is too long.

ENOENT

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

ENOMEM

Insufficient kernel memory was available.

ENOSPC

The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource.

ENOTDIR

mask contains IN_ONLYDIR and pathname is not a directory.

## VERSIONS
Inotify was merged into the 2.6.13 Linux kernel.

## CONFORMING TO
This system call is Linux-specific.

## EXAMPLES
See inotify(7).

## SEE ALSO
inotify_init(2), inotify_rm_watch(2), inotify(7)


title: inotify_init(2)

summary: initialize an inotify instance

text:
# inotify_init(2)

## NAME
inotify_init, inotify_init1 - initialize an inotify instance

## SYNOPSIS

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

```
int inotify_init(void);
int inotify_init1(int flags);
```

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

inotify_init() initializes a new inotify instance and returns a file descriptor associated with a new inotify event queue.

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

IN_NONBLOCK

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

IN_CLOEXEC

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

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

## ERRORS
EINVAL

(inotify_init1()) An invalid value was specified in flags.

EMFILE

The user limit on the total number of inotify instances has been reached.

EMFILE

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

ENFILE

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

ENOMEM

Insufficient kernel memory is available.

## VERSIONS
inotify_init() first appeared in Linux 2.6.13; library support was added to glibc in version 2.4. inotify_init1() was added in Linux 2.6.27; library support was added to glibc in version 2.9.

## CONFORMING TO
These system calls are Linux-specific.

## SEE ALSO
inotify_add_watch(2), inotify_rm_watch(2), inotify(7)


title: inotify_rm_watch(2)

text:
# inotify_rm_watch(2)

## NAME
inotify_rm_watch - remove an existing watch from an inotify instance

## SYNOPSIS

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

```
int inotify_rm_watch(int fd, int wd);
```

## DESCRIPTION
inotify_rm_watch() removes the watch associated with the watch descriptor wd from the inotify instance associated with the file descriptor fd.

Removing a watch causes an IN_IGNORED event to be generated for this watch descriptor. (See inotify(7).)

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

## ERRORS
EBADF

fd is not a valid file descriptor.

EINVAL

The watch descriptor wd is not valid; or fd is not an inotify file descriptor.

## VERSIONS
Inotify was merged into the 2.6.13 Linux kernel.

## CONFORMING TO
This system call is Linux-specific.

## SEE ALSO
inotify_add_watch(2), inotify_init(2), inotify(7)


intro

title: intro(2)

summary: introduction to system calls

text:
# intro(2)

## NAME
intro - introduction to system calls

## DESCRIPTION
Section 2 of the manual describes the Linux system calls. A system call is an entry point into the Linux kernel. Usually, system calls are not invoked directly: instead, most system calls have corresponding C library wrapper functions which perform the steps required (e.g., trapping to kernel mode) in order to invoke the system call. Thus, making a system call looks the same as invoking a normal library function.

In many cases, the C library wrapper function does nothing more than:

- copying arguments and the unique system call number to the registers where the kernel expects them;

- trapping to kernel mode, at which point the kernel does the real work of the system call;

- setting errno if the system call returns an error number when the kernel returns the CPU to user mode.

However, in a few cases, a wrapper function may do rather more than this, for example, performing some preprocessing of the arguments before trapping to kernel mode, or postprocessing of values returned by the system call. Where this is the case, the manual pages in Section 2 generally try to note the details of both the (usually GNU) C library API interface and the raw system call. Most commonly, the main DESCRIPTION will focus on the C library interface, and differences for the system call are covered in the NOTES section.

For a list of the Linux system calls, see syscalls(2).

## RETURN VALUE
On error, most system calls return a negative error number (i.e., the negated value of one of the constants described in errno(3)). The C library wrapper hides this detail from the caller: when a system call returns a negative value, the wrapper copies the absolute value into the errno variable, and returns -1 as the return value of the wrapper.

The value returned by a successful system call depends on the call. Many system calls return 0 on success, but some can return nonzero values from a successful call. The details are described in the individual manual pages.

In some cases, the programmer must define a feature test macro in order to obtain the declaration of a system call from the header file specified in the man page SYNOPSIS section. (Where required, these feature test macros must be defined before including any header files.) In such cases, the required macro is described in the man page. For further information on feature test macros, see feature_test_macros(7).

## CONFORMING TO
Certain terms and abbreviations are used to indicate UNIX variants and standards to which calls in this section conform. See standards(7).

## NOTES

### Calling directly
In most cases, it is unnecessary to invoke a system call directly, but there are times when the Standard C library does not implement a nice wrapper function for you. In this case, the programmer must manually invoke the system call using syscall(2). Historically, this was also possible using one of the _syscall macros described in _syscall(2).

### Authors and copyright conditions
Look at the header of the manual page source for the author(s) and copyright conditions. Note that these can be different from page to page!

## SEE ALSO
_syscall(2), syscall(2), syscalls(2), errno(3), intro(3), capabilities(7), credentials(7), feature_test_macros(7), mq_overview(7), path_resolution(7), pipe(7), pty(7), sem_overview(7), shm_overview(7), signal(7), socket(7), standards(7), system_data_types(7), symlink(7), sysvipc(7), time(7)


title: io_cancel(2)

text:
# io_cancel(2)

## NAME
io_cancel - cancel an outstanding asynchronous I/O operation

## SYNOPSIS

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

```
int syscall(SYS_io_cancel, aio_context_t ctx_id, struct iocb *iocb,
            struct io_event *result);
```

## DESCRIPTION
Note: this page describes the raw Linux system call interface. The wrapper function provided by libaio uses a different type for the ctx_id argument. See NOTES.

The io_cancel() system call attempts to cancel an asynchronous I/O operation previously submitted with io_submit(2). The iocb argument describes the operation to be canceled and the ctx_id argument is the AIO context to which the operation was submitted. If the operation is successfully canceled, the event will be copied into the memory pointed to by result without being placed into the completion queue.

## RETURN VALUE
On success, io_cancel() returns 0. For the failure return, see NOTES.

## ERRORS
EAGAIN

The iocb specified was not canceled.

EFAULT

One of the data structures points to invalid data.

EINVAL

The AIO context specified by ctx_id is invalid.

ENOSYS

io_cancel() is not implemented on this architecture.

## VERSIONS
The asynchronous I/O system calls first appeared in Linux 2.5.

## CONFORMING TO
io_cancel() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
You probably want to use the io_cancel() wrapper function provided by libaio.

Note that the libaio wrapper function uses a different type (io_context_t) for the ctx_id argument. Note also that the libaio wrapper does not follow the usual C library conventions for indicating errors: on error it returns a negated error number (the negative of one of the values listed in ERRORS). If the system call is invoked via syscall(2), then the return value follows the usual conventions for indicating an error: -1, with errno set to a (positive) value that indicates the error.

## SEE ALSO
io_destroy(2), io_getevents(2), io_setup(2), io_submit(2), aio(7)


title: io_destroy(2)

summary: destroy an asynchronous I/O context

text:
# io_destroy(2)

## NAME
io_destroy - destroy an asynchronous I/O context

## SYNOPSIS

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

```
int syscall(SYS_io_destroy, aio_context_t ctx_id);
```

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

## DESCRIPTION
Note: this page describes the raw Linux system call interface. The wrapper function provided by libaio uses a different type for the ctx_id argument. See NOTES.

The io_destroy() system call will attempt to cancel all outstanding asynchronous I/O operations against ctx_id, will block on the completion of all operations that could not be canceled, and will destroy the ctx_id.

## RETURN VALUE
On success, io_destroy() returns 0. For the failure return, see NOTES.

## ERRORS
EFAULT

The context pointed to is invalid.

EINVAL

The AIO context specified by ctx_id is invalid.

ENOSYS

io_destroy() is not implemented on this architecture.

## VERSIONS
The asynchronous I/O system calls first appeared in Linux 2.5.

## CONFORMING TO
io_destroy() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
You probably want to use the io_destroy() wrapper function provided by libaio.

Note that the libaio wrapper function uses a different type (io_context_t) for the ctx_id argument. Note also that the libaio wrapper does not follow the usual C library conventions for indicating errors: on error it returns a negated error number (the negative of one of the values listed in ERRORS). If the system call is invoked via syscall(2), then the return value follows the usual conventions for indicating an error: -1, with errno set to a (positive) value that indicates the error.

## SEE ALSO
io_cancel(2), io_getevents(2), io_setup(2), io_submit(2), aio(7)


title: io_getevents(2)

text:
# io_getevents(2)

## NAME
io_getevents - read asynchronous I/O events from the completion queue

## SYNOPSIS

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

```
int syscall(SYS_io_getevents, aio_context_t ctx_id,
            long min_nr, long nr, struct io_event *events,
            struct timespec *timeout);
```

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

## DESCRIPTION
Note: this page describes the raw Linux system call interface. The wrapper function provided by libaio uses a different type for the ctx_id argument. See NOTES.

The io_getevents() system call attempts to read at least min_nr events and up to nr events from the completion queue of the AIO context specified by ctx_id.

The timeout argument specifies the amount of time to wait for events, and is specified as a relative timeout in a structure of the following form:

```
struct timespec {

    time_t tv_sec;      /* seconds */

    long   tv_nsec;     /* nanoseconds [0 .. 999999999] */
};
```

The specified time will be rounded up to the system clock granularity and is guaranteed not to expire early.

Specifying timeout as NULL means block indefinitely until at least min_nr events have been obtained.

## RETURN VALUE
On success, io_getevents() returns the number of events read. This may be 0, or a value less than min_nr, if the timeout expired. It may also be a nonzero value less than min_nr, if the call was interrupted by a signal handler.

For the failure return, see NOTES.

## ERRORS
EFAULT

Either events or timeout is an invalid pointer.

EINTR

Interrupted by a signal handler; see signal(7).

EINVAL

ctx_id is invalid. min_nr is out of range or nr is out of range.

ENOSYS

io_getevents() is not implemented on this architecture.

## VERSIONS
The asynchronous I/O system calls first appeared in Linux 2.5.

## CONFORMING TO
io_getevents() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
You probably want to use the io_getevents() wrapper function provided by libaio.

Note that the libaio wrapper function uses a different type (io_context_t) for the ctx_id argument. Note also that the libaio wrapper does not follow the usual C library conventions for indicating errors: on error it returns a negated error number (the negative of one of the values listed in ERRORS). If the system call is invoked via syscall(2), then the return value follows the usual conventions for indicating an error: -1, with errno set to a (positive) value that indicates the error.

## BUGS
An invalid ctx_id may cause a segmentation fault instead of generating the error EINVAL.

## SEE ALSO
io_cancel(2), io_destroy(2), io_setup(2), io_submit(2), aio(7), time(7)


title: io_setup(2)

summary: create an asynchronous I/O context

text:
# io_setup(2)

## NAME
io_setup - create an asynchronous I/O context

## SYNOPSIS

```
#include <linux/aio_abi.h>          /* Defines needed types */
```

```
long io_setup(unsigned int nr_events, aio_context_t *ctx_idp);
```

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

## DESCRIPTION
Note: this page describes the raw Linux system call interface. The wrapper function provided by libaio uses a different type for the ctx_idp argument. See NOTES.

The io_setup() system call creates an asynchronous I/O context suitable for concurrently processing nr_events operations. The ctx_idp argument must not point to an AIO context that already exists, and must be initialized to 0 prior to the call. On successful creation of the AIO context, *ctx_idp is filled in with the resulting handle.

## RETURN VALUE
On success, io_setup() returns 0. For the failure return, see NOTES.

## ERRORS
EAGAIN

The specified nr_events exceeds the limit of available events, as defined in /proc/sys/fs/aio-max-nr (see proc(5)).

EFAULT

An invalid pointer is passed for ctx_idp.

EINVAL

ctx_idp is not initialized, or the specified nr_events exceeds internal limits. nr_events should be greater than 0.

ENOMEM

Insufficient kernel resources are available.

ENOSYS

io_setup() is not implemented on this architecture.

## VERSIONS
The asynchronous I/O system calls first appeared in Linux 2.5.

## CONFORMING TO
io_setup() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
Glibc does not provide a wrapper for this system call. You could invoke it using syscall(2). But instead, you probably want to use the io_setup() wrapper function provided by libaio.

Note that the libaio wrapper function uses a different type (io_context_t *) for the ctx_idp argument. Note also that the libaio wrapper does not follow the usual C library conventions for indicating errors: on error it returns a negated error number (the negative of one of the values listed in ERRORS). If the system call is invoked via syscall(2), then the return value follows the usual conventions for indicating an error: -1, with errno set to a (positive) value that indicates the error.

## SEE ALSO
io_cancel(2), io_destroy(2), io_getevents(2), io_submit(2), aio(7)


title: io_submit(2)

text:
# io_submit(2)

## NAME
io_submit - submit asynchronous I/O blocks for processing

## SYNOPSIS

```
#include <linux/aio_abi.h>          /* Defines needed types */
```

```
int io_submit(aio_context_t ctx_id, long nr, struct iocb **iocbpp);
```

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

## DESCRIPTION
Note: this page describes the raw Linux system call interface. The wrapper function provided by libaio uses a different type for the ctx_id argument. See NOTES.

The io_submit() system call queues nr I/O request blocks for processing in the AIO context ctx_id. The iocbpp argument should be an array of nr AIO control blocks, which will be submitted to context ctx_id.

The iocb (I/O control block) structure defined in linux/aio_abi.h defines the parameters that control the I/O operation.

```
#include <linux/aio_abi.h>
struct iocb {

    __u64   aio_data;

    __u32   PADDED(aio_key, aio_rw_flags);

    __u16   aio_lio_opcode;

    __s16   aio_reqprio;

    __u32   aio_fildes;

    __u64   aio_buf;

    __u64   aio_nbytes;

    __s64   aio_offset;

    __u64   aio_reserved2;

    __u32   aio_flags;

    __u32   aio_resfd;
};
```

The fields of this structure are as follows:

aio_data

This data is copied into the data field of the io_event structure upon I/O completion (see io_getevents(2)).

aio_key

This is an internal field used by the kernel. Do not modify this field after an io_submit() call.

aio_rw_flags

This defines the R/W flags passed with structure. The valid values are:

RWF_APPEND (since Linux 4.16)

Append data to the end of the file. See the description of the flag of the same name in pwritev2(2) as well as the description of O_APPEND in open(2). The aio_offset field is ignored. The file offset is not changed.

RWF_DSYNC (since Linux 4.13)

Write operation complete according to requirement of synchronized I/O data integrity. See the description of the flag of the same name in pwritev2(2) as well the description of O_DSYNC in open(2).

RWF_HIPRI (since Linux 4.13)

High priority request, poll if possible

RWF_NOWAIT (since Linux 4.14)

Don't wait if the I/O will block for operations such as file block allocations, dirty page flush, mutex locks, or a congested block device inside the kernel. If any of these conditions are met, the control block is returned immediately with a return value of -EAGAIN in the res field of the io_event structure (see io_getevents(2)).

RWF_SYNC (since Linux 4.13)

Write operation complete according to requirement of synchronized I/O file integrity. See the description of the flag of the same name in pwritev2(2) as well the description of O_SYNC in open(2).

aio_lio_opcode

This defines the type of I/O to be performed by the iocb structure. The valid values are defined by the enum defined in linux/aio_abi.h:

```
enum {

    IOCB_CMD_PREAD = 0,

    IOCB_CMD_PWRITE = 1,

    IOCB_CMD_FSYNC = 2,

    IOCB_CMD_FDSYNC = 3,

    IOCB_CMD_POLL = 5,

    IOCB_CMD_NOOP = 6,

    IOCB_CMD_PREADV = 7,

    IOCB_CMD_PWRITEV = 8,
};

```

aio_reqprio

This defines the requests priority.

aio_fildes

The file descriptor on which the I/O operation is to be performed.

aio_buf

This is the buffer used to transfer data for a read or write operation.

aio_nbytes

This is the size of the buffer pointed to by aio_buf.

aio_offset

This is the file offset at which the I/O operation is to be performed.

aio_flags

This is the set of flags associated with the iocb structure. The valid values are:

IOCB_FLAG_RESFD

Asynchronous I/O control must signal the file descriptor mentioned in aio_resfd upon completion.

IOCB_FLAG_IOPRIO (since Linux 4.18)

Interpret the aio_reqprio field as an IOPRIO_VALUE as defined by linux/ioprio.h.

aio_resfd

The file descriptor to signal in the event of asynchronous I/O completion.

## RETURN VALUE
On success, io_submit() returns the number of iocbs submitted (which may be less than nr, or 0 if nr is zero). For the failure return, see NOTES.

## ERRORS
EAGAIN

Insufficient resources are available to queue any iocbs.

EBADF

The file descriptor specified in the first iocb is invalid.

EFAULT

One of the data structures points to invalid data.

EINVAL

The AIO context specified by ctx_id is invalid. nr is less than 0. The iocb at *iocbpp[0] is not properly initialized, the operation specified is invalid for the file descriptor in the iocb, or the value in the aio_reqprio field is invalid.

ENOSYS

io_submit() is not implemented on this architecture.

EPERM

The aio_reqprio field is set with the class IOPRIO_CLASS_RT, but the submitting context does not have the CAP_SYS_ADMIN capability.

## VERSIONS
The asynchronous I/O system calls first appeared in Linux 2.5.

## CONFORMING TO
io_submit() is Linux-specific and should not be used in programs that are intended to be portable.

## NOTES
Glibc does not provide a wrapper for this system call. You could invoke it using syscall(2). But instead, you probably want to use the io_submit() wrapper function provided by libaio.

Note that the libaio wrapper function uses a different type (io_context_t) for the ctx_id argument. Note also that the libaio wrapper does not follow the usual C library conventions for indicating errors: on error it returns a negated error number (the negative of one of the values listed in ERRORS). If the system call is invoked via syscall(2), then the return value follows the usual conventions for indicating an error: -1, with errno set to a (positive) value that indicates the error.

## SEE ALSO
io_cancel(2), io_destroy(2), io_getevents(2), io_setup(2), aio(7)


ioctl

title: ioctl(2)

summary: control device

text:
# ioctl(2)

## NAME
ioctl - control device

## SYNOPSIS

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

```
int ioctl(int fd, unsigned long request, ...);
```

## DESCRIPTION
The ioctl() system call manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g., terminals) may be controlled with ioctl() requests. The argument fd must be an open file descriptor.

The second argument is a device-dependent request code. The third argument is an untyped pointer to memory. It's traditionally char *argp (from the days before void * was valid C), and will be so named for this discussion.

An ioctl() request has encoded in it whether the argument is an in parameter or out parameter, and the size of the argument argp in bytes. Macros and defines used in specifying an ioctl() request are located in the file <sys/ioctl.h>. See NOTES.

## RETURN VALUE
Usually, on success zero is returned. A few ioctl() requests use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EBADF

fd is not a valid file descriptor.

EFAULT

argp references an inaccessible memory area.

EINVAL

request or argp is not valid.

ENOTTY

fd is not associated with a character special device.

ENOTTY

The specified request does not apply to the kind of object that the file descriptor fd references.

## CONFORMING TO
No single standard. Arguments, returns, and semantics of ioctl() vary according to the device driver in question (the call is used as a catch-all for operations that don't cleanly fit the UNIX stream I/O model).

The ioctl() system call appeared in Version 7 AT&T UNIX.

## NOTES
In order to use this call, one needs an open file descriptor. Often the open(2) call has unwanted side effects, that can be avoided under Linux by giving it the O_NONBLOCK flag.

### ioctl structure
Ioctl command values are 32-bit constants. In principle these constants are completely arbitrary, but people have tried to build some structure into them.

The old Linux situation was that of mostly 16-bit constants, where the last byte is a serial number, and the preceding byte(s) give a type indicating the driver. Sometimes the major number was used: 0x03 for the HDIO_* ioctls, 0x06 for the LP* ioctls. And sometimes one or more ASCII letters were used. For example, TCGETS has value 0x00005401, with 0x54 = 'T' indicating the terminal driver, and CYGETTIMEOUT has value 0x00435906, with 0x43 0x59 = 'C' 'Y' indicating the cyclades driver.

Later (0.98p5) some more information was built into the number. One has 2 direction bits (00: none, 01: write, 10: read, 11: read/write) followed by 14 size bits (giving the size of the argument), followed by an 8-bit type (collecting the ioctls in groups for a common purpose or a common driver), and an 8-bit serial number.

The macros describing this structure live in <asm/ioctl.h> and are _IO(type,nr) and {_IOR,_IOW,_IOWR}(type,nr,size). They use sizeof(size) so that size is a misnomer here: this third argument is a data type.

Note that the size bits are very unreliable: in lots of cases they are wrong, either because of buggy macros using sizeof(sizeof(struct)), or because of legacy values.

Thus, it seems that the new structure only gave disadvantages: it does not help in checking, but it causes varying values for the various architectures.

## SEE ALSO
execve(2), fcntl(2), ioctl_console(2), ioctl_fat(2), ioctl_ficlonerange(2), ioctl_fideduperange(2), ioctl_fslabel(2), ioctl_getfsmap(2), ioctl_iflags(2), ioctl_ns(2), ioctl_tty(2), ioctl_userfaultfd(2), open(2), sd(4), tty(4)


title: ioctl_console(2)

text:
# ioctl_console(2)

## NAME
ioctl_console - ioctls for console terminal and virtual consoles

## DESCRIPTION
The following Linux-specific ioctl(2) requests are supported for console terminals and virtual consoles. Each requires a third argument, assumed here to be argp.

KDGETLED

Get state of LEDs. argp points to a char. The lower three bits of *argp are set to the state of the LEDs, as follows: LED_CAP

0x04

caps lock led

LED_NUM

0x02

num lock led

LED_SCR

0x01

scroll lock led

KDSETLED

Set the LEDs. The LEDs are set to correspond to the lower three bits of the unsigned long integer in argp. However, if a higher order bit is set, the LEDs revert to normal: displaying the state of the keyboard functions of caps lock, num lock, and scroll lock.

Before Linux 1.1.54, the LEDs just reflected the state of the corresponding keyboard flags, and KDGETLED/KDSETLED would also change the keyboard flags. Since Linux 1.1.54 the LEDs can be made to display arbitrary information, but by default they display the keyboard flags. The following two ioctls are used to access the keyboard flags.

KDGKBLED

Get keyboard flags CapsLock, NumLock, ScrollLock (not lights). argp points to a char which is set to the flag state. The low order three bits (mask 0x7) get the current flag state, and the low order bits of the next nibble (mask 0x70) get the default flag state. (Since Linux 1.1.54.)

KDSKBLED

Set keyboard flags CapsLock, NumLock, ScrollLock (not lights). argp is an unsigned long integer that has the desired flag state. The low order three bits (mask 0x7) have the flag state, and the low order bits of the next nibble (mask 0x70) have the default flag state. (Since Linux 1.1.54.)

KDGKBTYPE

Get keyboard type. This returns the value KB_101, defined as 0x02.

KDADDIO

Add I/O port as valid. Equivalent to ioperm(arg,1,1).

KDDELIO

Delete I/O port as valid. Equivalent to ioperm(arg,1,0).

KDENABIO

Enable I/O to video board. Equivalent to ioperm(0x3b4, 0x3df-0x3b4+1, 1).

KDDISABIO

Disable I/O to video board. Equivalent to ioperm(0x3b4, 0x3df-0x3b4+1, 0).

KDSETMODE

Set text/graphics mode. argp is an unsigned integer containing one of: KD_TEXT

0x00

KD_GRAPHICS

0x01

KDGETMODE

Get text/graphics mode. argp points to an int which is set to one of the values shown above for KDSETMODE.

KDMKTONE

Generate tone of specified length. The lower 16 bits of the unsigned long integer in argp specify the period in clock cycles, and the upper 16 bits give the duration in msec. If the duration is zero, the sound is turned off. Control returns immediately. For example, argp = (125<<16) + 0x637 would specify the beep normally associated with a ctrl-G. (Thus since Linux 0.99pl1; broken in Linux 2.1.49-50.)

KIOCSOUND

Start or stop sound generation. The lower 16 bits of argp specify the period in clock cycles (that is, argp = 1193180/frequency). argp = 0 turns sound off. In either case, control returns immediately.

GIO_CMAP

Get the current default color map from kernel. argp points to a 48-byte array. (Since Linux 1.3.3.)

PIO_CMAP

Change the default text-mode color map. argp points to a 48-byte array which contains, in order, the Red, Green, and Blue values for the 16 available screen colors: 0 is off, and 255 is full intensity. The default colors are, in order: black, dark red, dark green, brown, dark blue, dark purple, dark cyan, light grey, dark grey, bright red, bright green, yellow, bright blue, bright purple, bright cyan, and white. (Since Linux 1.3.3.)

GIO_FONT

Gets 256-character screen font in expanded form. argp points to an 8192-byte array. Fails with error code EINVAL if the currently loaded font is a 512-character font, or if the console is not in text mode.

GIO_FONTX

Gets screen font and associated information. argp points to a struct consolefontdesc (see PIO_FONTX). On call, the charcount field should be set to the maximum number of characters that would fit in the buffer pointed to by chardata. On return, the charcount and charheight are filled with the respective data for the currently loaded font, and the chardata array contains the font data if the initial value of charcount indicated enough space was available; otherwise the buffer is untouched and errno is set to ENOMEM. (Since Linux 1.3.1.)

PIO_FONT

Sets 256-character screen font. Load font into the EGA/VGA character generator. argp points to an 8192-byte map, with 32 bytes per character. Only the first N of them are used for an 8xN font (0 < N <= 32). This call also invalidates the Unicode mapping.

PIO_FONTX

Sets screen font and associated rendering information. argp points to a

```
struct consolefontdesc {

    unsigned short charcount;  /* characters in font

                                  (256 or 512) */

    unsigned short charheight; /* scan lines per

                                  character (1-32) */

    char          *chardata;   /* font data in

                                  expanded form */
};

```

If necessary, the screen will be appropriately resized, and SIGWINCH sent to the appropriate processes. This call also invalidates the Unicode mapping. (Since Linux 1.3.1.)

PIO_FONTRESET

Resets the screen font, size, and Unicode mapping to the bootup defaults. argp is unused, but should be set to NULL to ensure compatibility with future versions of Linux. (Since Linux 1.3.28.)

GIO_SCRNMAP

Get screen mapping from kernel. argp points to an area of size E_TABSZ, which is loaded with the font positions used to display each character. This call is likely to return useless information if the currently loaded font is more than 256 characters.

GIO_UNISCRNMAP

Get full Unicode screen mapping from kernel. argp points to an area of size E_TABSZ*sizeof(unsigned short), which is loaded with the Unicodes each character represent. A special set of Unicodes, starting at U+F000, are used to represent "direct to font" mappings. (Since Linux 1.3.1.)

PIO_SCRNMAP

Loads the "user definable" (fourth) table in the kernel which maps bytes into console screen symbols. argp points to an area of size E_TABSZ.

PIO_UNISCRNMAP

Loads the "user definable" (fourth) table in the kernel which maps bytes into Unicodes, which are then translated into screen symbols according to the currently loaded Unicode-to-font map. Special Unicodes starting at U+F000 can be used to map directly to the font symbols. (Since Linux 1.3.1.)

GIO_UNIMAP

Get Unicode-to-font mapping from kernel. argp points to a

```
struct unimapdesc {

    unsigned short  entry_ct;

    struct unipair *entries;
};

```

where entries points to an array of

```
struct unipair {

    unsigned short unicode;

    unsigned short fontpos;
};

```

(Since Linux 1.1.92.)

PIO_UNIMAP

Put unicode-to-font mapping in kernel. argp points to a struct unimapdesc. (Since Linux 1.1.92)

PIO_UNIMAPCLR

Clear table, possibly advise hash algorithm. argp points to a

```
struct unimapinit {

    unsigned short advised_hashsize;  /* 0 if no opinion */

    unsigned short advised_hashstep;  /* 0 if no opinion */

    unsigned short advised_hashlevel; /* 0 if no opinion */
};

```

(Since Linux 1.1.92.)

KDGKBMODE

Gets current keyboard mode. argp points to a long which is set to one of these: K_RAW

0x00 /* Raw (scancode) mode */

K_XLATE

0x01 /* Translate keycodes using keymap */

K_MEDIUMRAW

0x02 /* Medium raw (scancode) mode */

K_UNICODE

0x03 /* Unicode mode */

K_OFF

0x04 /* Disabled mode; since Linux 2.6.39 */

KDSKBMODE

Sets current keyboard mode. argp is a long equal to one of the values shown for KDGKBMODE.

KDGKBMETA

Gets meta key handling mode. argp points to a long which is set to one of these: K_METABIT

0x03

set high order bit

K_ESCPREFIX

0x04

escape prefix

KDSKBMETA

Sets meta key handling mode. argp is a long equal to one of the values shown above for KDGKBMETA.

KDGKBENT

Gets one entry in key translation table (keycode to action code). argp points to a

```
struct kbentry {

    unsigned char  kb_table;

    unsigned char  kb_index;

    unsigned short kb_value;
};

```

with the first two members filled in: kb_table selects the key table (0 <= kb_table < MAX_NR_KEYMAPS), and kb_index is the keycode (0 <= kb_index < NR_KEYS). kb_value is set to the corresponding action code, or K_HOLE if there is no such key, or K_NOSUCHMAP if kb_table is invalid.

KDSKBENT

Sets one entry in translation table. argp points to a struct kbentry.

KDGKBSENT

Gets one function key string. argp points to a

```
struct kbsentry {

    unsigned char kb_func;

    unsigned char kb_string[512];
};

```

kb_string is set to the (null-terminated) string corresponding to the kb_functh function key action code.

KDSKBSENT

Sets one function key string entry. argp points to a struct kbsentry.

KDGKBDIACR

Read kernel accent table. argp points to a

```
struct kbdiacrs {

    unsigned int   kb_cnt;

    struct kbdiacr kbdiacr[256];
};

```

where kb_cnt is the number of entries in the array, each of which is a

```
struct kbdiacr {

    unsigned char diacr;

    unsigned char base;

    unsigned char result;
};

```

KDGETKEYCODE

Read kernel keycode table entry (scan code to keycode). argp points to a

```
struct kbkeycode {

    unsigned int scancode;

    unsigned int keycode;
};

```

keycode is set to correspond to the given scancode. (89 <= scancode <= 255 only. For 1 <= scancode <= 88, keycode==scancode.) (Since Linux 1.1.63.)

KDSETKEYCODE

Write kernel keycode table entry. argp points to a struct kbkeycode. (Since Linux 1.1.63.)

KDSIGACCEPT

The calling process indicates its willingness to accept the signal argp when it is generated by pressing an appropriate key combination. (1 <= argp <= NSIG). (See spawn_console() in linux/drivers/char/keyboard.c.)

VT_OPENQRY

Returns the first available (non-opened) console. argp points to an int which is set to the number of the vt (1 <= *argp <= MAX_NR_CONSOLES).

VT_GETMODE

Get mode of active vt. argp points to a

```
struct vt_mode {

    char  mode;    /* vt mode */

    char  waitv;   /* if set, hang on writes if not active */

    short relsig;  /* signal to raise on release req */

    short acqsig;  /* signal to raise on acquisition */

    short frsig;   /* unused (set to 0) */
};

```

which is set to the mode of the active vt. mode is set to one of these values: VT_AUTO

auto vt switching

VT_PROCESS

process controls switching

VT_ACKACQ

acknowledge switch

VT_SETMODE

Set mode of active vt. argp points to a struct vt_mode.

VT_GETSTATE

Get global vt state info. argp points to a

```
struct vt_stat {

    unsigned short v_active;  /* active vt */

    unsigned short v_signal;  /* signal to send */

    unsigned short v_state;   /* vt bit mask */
};

```

For each vt in use, the corresponding bit in the v_state member is set. (Kernels 1.0 through 1.1.92.)

VT_RELDISP

Release a display.

VT_ACTIVATE

Switch to vt argp (1 <= argp <= MAX_NR_CONSOLES).

VT_WAITACTIVE

Wait until vt argp has been activated.

VT_DISALLOCATE

Deallocate the memory associated with vt argp. (Since Linux 1.1.54.)

VT_RESIZE

Set the kernel's idea of screensize. argp points to a

```
struct vt_sizes {

    unsigned short v_rows;       /* # rows */

    unsigned short v_cols;       /* # columns */

    unsigned short v_scrollsize; /* no longer used */
};

```

Note that this does not change the videomode. See resizecons(8). (Since Linux 1.1.54.)

VT_RESIZEX

Set the kernel's idea of various screen parameters. argp points to a

```
struct vt_consize {

    unsigned short v_rows;  /* number of rows */

    unsigned short v_cols;  /* number of columns */

    unsigned short v_vlin;  /* number of pixel rows

                               on screen */

    unsigned short v_clin;  /* number of pixel rows

                               per character */

    unsigned short v_vcol;  /* number of pixel columns

                               on screen */

    unsigned short v_ccol;  /* number of pixel columns

                               per character */
};

```

Any parameter may be set to zero, indicating "no change", but if multiple parameters are set, they must be self-consistent. Note that this does not change the videomode. See resizecons(8). (Since Linux 1.3.3.)

The action of the following ioctls depends on the first byte in the struct pointed to by argp, referred to here as the subcode. These are legal only for the superuser or the owner of the current terminal.

TIOCLINUX, subcode=0

Dump the screen. Disappeared in Linux 1.1.92. (With kernel 1.1.92 or later, read from /dev/vcsN or /dev/vcsaN instead.)

TIOCLINUX, subcode=1

Get task information. Disappeared in Linux 1.1.92.

TIOCLINUX, subcode=2

Set selection. argp points to a

```
struct {

    char  subcode;

    short xs, ys, xe, ye;

    short sel_mode;
};

```

xs and ys are the starting column and row. xe and ye are the ending column and row. (Upper left corner is row=column=1.) sel_mode is 0 for character-by-character selection, 1 for word-by-word selection, or 2 for line-by-line selection. The indicated screen characters are highlighted and saved in the static array sel_buffer in devices/char/console.c.

TIOCLINUX, subcode=3

Paste selection. The characters in the selection buffer are written to fd.

TIOCLINUX, subcode=4

Unblank the screen.

TIOCLINUX, subcode=5

Sets contents of a 256-bit look up table defining characters in a "word", for word-by-word selection. (Since Linux 1.1.32.)

TIOCLINUX, subcode=6

argp points to a char which is set to the value of the kernel variable shift_state. (Since Linux 1.1.32.)

TIOCLINUX, subcode=7

argp points to a char which is set to the value of the kernel variable report_mouse. (Since Linux 1.1.33.)

TIOCLINUX, subcode=8

Dump screen width and height, cursor position, and all the character-attribute pairs. (Kernels 1.1.67 through 1.1.91 only. With kernel 1.1.92 or later, read from /dev/vcsa* instead.)

TIOCLINUX, subcode=9

Restore screen width and height, cursor position, and all the character-attribute pairs. (Kernels 1.1.67 through 1.1.91 only. With kernel 1.1.92 or later, write to /dev/vcsa* instead.)

TIOCLINUX, subcode=10

Handles the Power Saving feature of the new generation of monitors. VESA screen blanking mode is set to argp[1], which governs what screen blanking does:

0:

Screen blanking is disabled.

1:

The current video adapter register settings are saved, then the controller is programmed to turn off the vertical synchronization pulses. This puts the monitor into "standby" mode. If your monitor has an Off_Mode timer, then it will eventually power down by itself.

2:

The current settings are saved, then both the vertical and horizontal synchronization pulses are turned off. This puts the monitor into "off" mode. If your monitor has no Off_Mode timer, or if you want your monitor to power down immediately when the blank_timer times out, then you choose this option. (Caution: Powering down frequently will damage the monitor.) (Since Linux 1.1.76.)

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

## ERRORS
EBADF

The file descriptor is invalid.

EINVAL

The file descriptor or argp is invalid.

ENOTTY

The file descriptor is not associated with a character special device, or the specified request does not apply to it.

EPERM

Insufficient permission.

## NOTES
Warning: Do not regard this man page as documentation of the Linux console ioctls. This is provided for the curious only, as an alternative to reading the source. Ioctl's are undocumented Linux internals, liable to be changed without warning. (And indeed, this page more or less describes the situation as of kernel version 1.1.94; there are many minor and not-so-minor differences with earlier versions.)

Very often, ioctls are introduced for communication between the kernel and one particular well-known program (fdisk, hdparm, setserial, tunelp, loadkeys, selection, setfont, etc.), and their behavior will be changed when required by this particular program.

Programs using these ioctls will not be portable to other versions of UNIX, will not work on older versions of Linux, and will not work on future versions of Linux.

Use POSIX functions.

## SEE ALSO
dumpkeys(1), kbd_mode(1), loadkeys(1), mknod(1), setleds(1), setmetamode(1), execve(2), fcntl(2), ioctl_tty(2), ioperm(2), termios(3), console_codes(4), mt(4), sd(4), tty(4), ttyS(4), vcs(4), vcsa(4), charsets(7), mapscrn(8), resizecons(8), setfont(8)

/usr/include/linux/kd.h, /usr/include/linux/vt.h