rtld-audit

title: rtld-audit(7)

summary: auditing API for the dynamic linker

text:
# rtld-audit(7)

## NAME
rtld-audit - auditing API for the dynamic linker

## SYNOPSIS

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

## DESCRIPTION
The GNU dynamic linker (run-time linker) provides an auditing API that allows an application to be notified when various dynamic linking events occur. This API is very similar to the auditing interface provided by the Solaris run-time linker. The necessary constants and prototypes are defined by including <link.h>.

To use this interface, the programmer creates a shared library that implements a standard set of function names. Not all of the functions need to be implemented: in most cases, if the programmer is not interested in a particular class of auditing event, then no implementation needs to be provided for the corresponding auditing function.

To employ the auditing interface, the environment variable LD_AUDIT must be defined to contain a colon-separated list of shared libraries, each of which can implement (parts of) the auditing API. When an auditable event occurs, the corresponding function is invoked in each library, in the order that the libraries are listed.

### la_version()

```
unsigned int la_version(unsigned int version);
```

This is the only function that must be defined by an auditing library: it performs the initial handshake between the dynamic linker and the auditing library. When invoking this function, the dynamic linker passes, in version, the highest version of the auditing interface that the linker supports.

A typical implementation of this function simply returns the constant LAV_CURRENT, which indicates the version of <link.h> that was used to build the audit module. If the dynamic linker does not support this version of the audit interface, it will refuse to activate this audit module. If the function returns zero, the dynamic linker also does not activate this audit module.

In order to enable backwards compatibility with older dynamic linkers, an audit module can examine the version argument and return an earlier version than LAV_CURRENT, assuming the module can adjust its implementation to match the requirements of the previous version of the audit interface. The la_version function should not return the value of version without further checks because it could correspond to an interface that does not match the <link.h> definitions used to build the audit module.

### la_objsearch()

```
char *la_objsearch(const char *name, uintptr_t *cookie,
                   unsigned int flag);
```

The dynamic linker invokes this function to inform the auditing library that it is about to search for a shared object. The name argument is the filename or pathname that is to be searched for. cookie identifies the shared object that initiated the search. flag is set to one of the following values:

LA_SER_ORIG

This is the original name that is being searched for. Typically, this name comes from an ELF DT_NEEDED entry, or is the filename argument given to dlopen(3).

LA_SER_LIBPATH

name was created using a directory specified in LD_LIBRARY_PATH.

LA_SER_RUNPATH

name was created using a directory specified in an ELF DT_RPATH or DT_RUNPATH list.

LA_SER_CONFIG

name was found via the ldconfig(8) cache (/etc/ld.so.cache).

LA_SER_DEFAULT

name was found via a search of one of the default directories.

LA_SER_SECURE

name is specific to a secure object (unused on Linux).

As its function result, la_objsearch() returns the pathname that the dynamic linker should use for further processing. If NULL is returned, then this pathname is ignored for further processing. If this audit library simply intends to monitor search paths, then name should be returned.

### la_activity()

```
void la_activity( uintptr_t *cookie, unsigned int flag);
```

The dynamic linker calls this function to inform the auditing library that link-map activity is occurring. cookie identifies the object at the head of the link map. When the dynamic linker invokes this function, flag is set to one of the following values:

LA_ACT_ADD

New objects are being added to the link map.

LA_ACT_DELETE

Objects are being removed from the link map.

LA_ACT_CONSISTENT

Link-map activity has been completed: the map is once again consistent.

### la_objopen()

```
unsigned int la_objopen(struct link_map *map, Lmid_t lmid,
                        uintptr_t *cookie);
```

The dynamic linker calls this function when a new shared object is loaded. The map argument is a pointer to a link-map structure that describes the object. The lmid field has one of the following values

LM_ID_BASE

Link map is part of the initial namespace.

LM_ID_NEWLM

Link map is part of a new namespace requested via dlmopen(3).

cookie is a pointer to an identifier for this object. The identifier is provided to later calls to functions in the auditing library in order to identify this object. This identifier is initialized to point to object's link map, but the audit library can change the identifier to some other value that it may prefer to use to identify the object.

As its return value, la_objopen() returns a bit mask created by ORing zero or more of the following constants, which allow the auditing library to select the objects to be monitored by la_symbind*():

LA_FLG_BINDTO

Audit symbol bindings to this object.

LA_FLG_BINDFROM

Audit symbol bindings from this object.

A return value of 0 from la_objopen() indicates that no symbol bindings should be audited for this object.

### la_objclose()

```
unsigned int la_objclose(uintptr_t *cookie);
```

The dynamic linker invokes this function after any finalization code for the object has been executed, before the object is unloaded. The cookie argument is the identifier obtained from a previous invocation of la_objopen().

In the current implementation, the value returned by la_objclose() is ignored.

### la_preinit()

```
void la_preinit(uintptr_t *cookie);
```

The dynamic linker invokes this function after all shared objects have been loaded, before control is passed to the application (i.e., before calling main()). Note that main() may still later dynamically load objects using dlopen(3).

### la_symbind*()

```
uintptr_t la_symbind32(Elf32_Sym *sym, unsigned int ndx,
                       uintptr_t *refcook, uintptr_t *defcook,
                       unsigned int *flags, const char *symname);
uintptr_t la_symbind64(Elf64_Sym *sym, unsigned int ndx,
                       uintptr_t *refcook, uintptr_t *defcook,
                       unsigned int *flags, const char *symname);
```

The dynamic linker invokes one of these functions when a symbol binding occurs between two shared objects that have been marked for auditing notification by la_objopen(). The la_symbind32() function is employed on 32-bit platforms; the la_symbind64() function is employed on 64-bit platforms.

The sym argument is a pointer to a structure that provides information about the symbol being bound. The structure definition is shown in <elf.h>. Among the fields of this structure, st_value indicates the address to which the symbol is bound.

The ndx argument gives the index of the symbol in the symbol table of the bound shared object.

The refcook argument identifies the shared object that is making the symbol reference; this is the same identifier that is provided to the la_objopen() function that returned LA_FLG_BINDFROM. The defcook argument identifies the shared object that defines the referenced symbol; this is the same identifier that is provided to the la_objopen() function that returned LA_FLG_BINDTO.

The symname argument points a string containing the name of the symbol.

The flags argument is a bit mask that both provides information about the symbol and can be used to modify further auditing of this PLT (Procedure Linkage Table) entry. The dynamic linker may supply the following bit values in this argument:

LA_SYMB_DLSYM

The binding resulted from a call to dlsym(3).

LA_SYMB_ALTVALUE

A previous la_symbind*() call returned an alternate value for this symbol.

By default, if the auditing library implements la_pltenter() and la_pltexit() functions (see below), then these functions are invoked, after la_symbind(), for PLT entries, each time the symbol is referenced. The following flags can be ORed into *flags to change this default behavior:

LA_SYMB_NOPLTENTER

Don't call la_pltenter() for this symbol.

LA_SYMB_NOPLTEXIT

Don't call la_pltexit() for this symbol.

The return value of la_symbind32() and la_symbind64() is the address to which control should be passed after the function returns. If the auditing library is simply monitoring symbol bindings, then it should return sym->st_value. A different value may be returned if the library wishes to direct control to an alternate location.

### la_pltenter()
The precise name and argument types for this function depend on the hardware platform. (The appropriate definition is supplied by <link.h>.) Here is the definition for x86-32:

```
Elf32_Addr la_i86_gnu_pltenter(Elf32_Sym *sym, unsigned int ndx,
                 uintptr_t *refcook, uintptr_t *defcook,
                 La_i86_regs *regs, unsigned int *flags,
                 const char *symname, long *framesizep);
```

This function is invoked just before a PLT entry is called, between two shared objects that have been marked for binding notification.

The sym, ndx, refcook, defcook, and symname are as for la_symbind*().

The regs argument points to a structure (defined in <link.h>) containing the values of registers to be used for the call to this PLT entry.

The flags argument points to a bit mask that conveys information about, and can be used to modify subsequent auditing of, this PLT entry, as for la_symbind*().

The framesizep argument points to a long int buffer that can be used to explicitly set the frame size used for the call to this PLT entry. If different la_pltenter() invocations for this symbol return different values, then the maximum returned value is used. The la_pltexit() function is called only if this buffer is explicitly set to a suitable value.

The return value of la_pltenter() is as for la_symbind*().

### la_pltexit()
The precise name and argument types for this function depend on the hardware platform. (The appropriate definition is supplied by <link.h>.) Here is the definition for x86-32:

```
unsigned int la_i86_gnu_pltexit(Elf32_Sym *sym, unsigned int ndx,
                 uintptr_t *refcook, uintptr_t *defcook,
                 const La_i86_regs *inregs, La_i86_retval *outregs,
                 const char *symname);
```

This function is called when a PLT entry, made between two shared objects that have been marked for binding notification, returns. The function is called just before control returns to the caller of the PLT entry.

The sym, ndx, refcook, defcook, and symname are as for la_symbind*().

The inregs argument points to a structure (defined in <link.h>) containing the values of registers used for the call to this PLT entry. The outregs argument points to a structure (defined in <link.h>) containing return values for the call to this PLT entry. These values can be modified by the caller, and the changes will be visible to the caller of the PLT entry.

In the current GNU implementation, the return value of la_pltexit() is ignored.

## CONFORMING TO
This API is nonstandard, but very similar to the Solaris API, described in the Solaris Linker and Libraries Guide, in the chapter Runtime Linker Auditing Interface.

## NOTES
Note the following differences from the Solaris dynamic linker auditing API:

- The Solaris la_objfilter() interface is not supported by the GNU implementation.

- The Solaris la_symbind32() and la_pltexit() functions do not provide a symname argument.

- The Solaris la_pltexit() function does not provide inregs and outregs arguments (but does provide a retval argument with the function return value).

## BUGS
In glibc versions up to and include 2.9, specifying more than one audit library in LD_AUDIT results in a run-time crash. This is reportedly fixed in glibc 2.10.

## EXAMPLES

```
#include <link.h>
#include <stdio.h>
unsigned int
la_version(unsigned int version)
{

    printf("la_version(): version = %u; LAV_CURRENT = %u\n",

            version, LAV_CURRENT);

    return LAV_CURRENT;
}
char *
la_objsearch(const char *name, uintptr_t *cookie, unsigned int flag)
{

    printf("la_objsearch(): name = %s; cookie = %p", name, cookie);

    printf("; flag = %s\n",

            (flag == LA_SER_ORIG) ?    "LA_SER_ORIG" :

            (flag == LA_SER_LIBPATH) ? "LA_SER_LIBPATH" :

            (flag == LA_SER_RUNPATH) ? "LA_SER_RUNPATH" :

            (flag == LA_SER_DEFAULT) ? "LA_SER_DEFAULT" :

            (flag == LA_SER_CONFIG) ?  "LA_SER_CONFIG" :

            (flag == LA_SER_SECURE) ?  "LA_SER_SECURE" :

            "???");

    return name;
}
void
la_activity (uintptr_t *cookie, unsigned int flag)
{

    printf("la_activity(): cookie = %p; flag = %s\n", cookie,

            (flag == LA_ACT_CONSISTENT) ? "LA_ACT_CONSISTENT" :

            (flag == LA_ACT_ADD) ?        "LA_ACT_ADD" :

            (flag == LA_ACT_DELETE) ?     "LA_ACT_DELETE" :

            "???");
}
unsigned int
la_objopen(struct link_map *map, Lmid_t lmid, uintptr_t *cookie)
{

    printf("la_objopen(): loading \"%s\"; lmid = %s; cookie=%p\n",

            map->l_name,

            (lmid == LM_ID_BASE) ?  "LM_ID_BASE" :

            (lmid == LM_ID_NEWLM) ? "LM_ID_NEWLM" :

            "???",

            cookie);

    return LA_FLG_BINDTO | LA_FLG_BINDFROM;
}
unsigned int
la_objclose (uintptr_t *cookie)
{

    printf("la_objclose(): %p\n", cookie);

    return 0;
}
void
la_preinit(uintptr_t *cookie)
{

    printf("la_preinit(): %p\n", cookie);
}
uintptr_t
la_symbind32(Elf32_Sym *sym, unsigned int ndx, uintptr_t *refcook,

        uintptr_t *defcook, unsigned int *flags, const char *symname)
{

    printf("la_symbind32(): symname = %s; sym->st_value = %p\n",

            symname, sym->st_value);

    printf("        ndx = %u; flags = %#x", ndx, *flags);

    printf("; refcook = %p; defcook = %p\n", refcook, defcook);

    return sym->st_value;
}
uintptr_t
la_symbind64(Elf64_Sym *sym, unsigned int ndx, uintptr_t *refcook,

        uintptr_t *defcook, unsigned int *flags, const char *symname)
{

    printf("la_symbind64(): symname = %s; sym->st_value = %p\n",

            symname, sym->st_value);

    printf("        ndx = %u; flags = %#x", ndx, *flags);

    printf("; refcook = %p; defcook = %p\n", refcook, defcook);

    return sym->st_value;
}
Elf32_Addr
la_i86_gnu_pltenter(Elf32_Sym *sym, unsigned int ndx,

        uintptr_t *refcook, uintptr_t *defcook, La_i86_regs *regs,

        unsigned int *flags, const char *symname, long *framesizep)
{

    printf("la_i86_gnu_pltenter(): %s (%p)\n", symname, sym->st_value);

    return sym->st_value;
}
```

## SEE ALSO
ldd(1), dlopen(3), ld.so(8), ldconfig(8)


rtnetlink

package: man-pages

title: rtnetlink(7)

summary: Linux routing socket

text:
# rtnetlink(7)

## NAME
rtnetlink - Linux routing socket

## SYNOPSIS

```
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>
```

```
rtnetlink_socket = socket(AF_NETLINK, int socket_type, NETLINK_ROUTE);
```

## DESCRIPTION
Rtnetlink allows the kernel's routing tables to be read and altered. It is used within the kernel to communicate between various subsystems, though this usage is not documented here, and for communication with user-space programs. Network routes, IP addresses, link parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers may all be controlled through NETLINK_ROUTE sockets. It is based on netlink messages; see netlink(7) for more information.

### Routing attributes
Some rtnetlink messages have optional attributes after the initial header:

```
struct rtattr {

    unsigned short rta_len;    /* Length of option */

    unsigned short rta_type;   /* Type of option */

    /* Data follows */
};
```

These attributes should be manipulated using only the RTA_* macros or libnetlink, see rtnetlink(3).

### Messages
Rtnetlink consists of these message types (in addition to standard netlink messages):

RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK

Create, remove, or get information about a specific network interface. These messages contain an ifinfomsg structure followed by a series of rtattr structures.

```
struct ifinfomsg {

    unsigned char  ifi_family; /* AF_UNSPEC */

    unsigned short ifi_type;   /* Device type */

    int            ifi_index;  /* Interface index */

    unsigned int   ifi_flags;  /* Device flags  */

    unsigned int   ifi_change; /* change mask */
};

```

ifi_flags contains the device flags, see netdevice(7); ifi_index is the unique interface index (since Linux 3.7, it is possible to feed a nonzero value with the RTM_NEWLINK message, thus creating a link with the given ifindex); ifi_change is reserved for future use and should be always set to 0xFFFFFFFF. Routing attributes

rta_type

Value type

Description

IFLA_UNSPEC

-

unspecified

IFLA_ADDRESS

hardware address

interface L2 address

IFLA_BROADCAST

hardware address

L2 broadcast address

IFLA_IFNAME

asciiz string

Device name

IFLA_MTU

unsigned int

MTU of the device

IFLA_LINK

int

Link type

IFLA_QDISC

asciiz string

Queueing discipline

IFLA_STATS

see below

Interface Statistics

The value type for IFLA_STATS is struct rtnl_link_stats (struct net_device_stats in Linux 2.4 and earlier).

RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR

Add, remove, or receive information about an IP address associated with an interface. In Linux 2.2, an interface can carry multiple IP addresses, this replaces the alias device concept in 2.0. In Linux 2.2, these messages support IPv4 and IPv6 addresses. They contain an ifaddrmsg structure, optionally followed by rtattr routing attributes.

```
struct ifaddrmsg {

    unsigned char ifa_family;    /* Address type */

    unsigned char ifa_prefixlen; /* Prefixlength of address */

    unsigned char ifa_flags;     /* Address flags */

    unsigned char ifa_scope;     /* Address scope */

    unsigned int  ifa_index;     /* Interface index */
};

```

ifa_family is the address family type (currently AF_INET or AF_INET6), ifa_prefixlen is the length of the address mask of the address if defined for the family (like for IPv4), ifa_scope is the address scope, ifa_index is the interface index of the interface the address is associated with. ifa_flags is a flag word of IFA_F_SECONDARY for secondary address (old alias interface), IFA_F_PERMANENT for a permanent address set by the user and other undocumented flags. Attributes

rta_type

Value type

Description

IFA_UNSPEC

-

unspecified

IFA_ADDRESS

raw protocol address

interface address

IFA_LOCAL

raw protocol address

local address

IFA_LABEL

asciiz string

name of the interface

IFA_BROADCAST

raw protocol address

broadcast address

IFA_ANYCAST

raw protocol address

anycast address

IFA_CACHEINFO

struct ifa_cacheinfo

Address information

RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE

Create, remove, or receive information about a network route. These messages contain an rtmsg structure with an optional sequence of rtattr structures following. For RTM_GETROUTE, setting rtm_dst_len and rtm_src_len to 0 means you get all entries for the specified routing table. For the other fields, except rtm_table and rtm_protocol, 0 is the wildcard.

```
struct rtmsg {

    unsigned char rtm_family;   /* Address family of route */

    unsigned char rtm_dst_len;  /* Length of destination */

    unsigned char rtm_src_len;  /* Length of source */

    unsigned char rtm_tos;      /* TOS filter */

    unsigned char rtm_table;    /* Routing table ID;

                                   see RTA_TABLE below */

    unsigned char rtm_protocol; /* Routing protocol; see below */

    unsigned char rtm_scope;    /* See below */

    unsigned char rtm_type;     /* See below */

    unsigned int  rtm_flags;
};

```

rtm_type

Route type

RTN_UNSPEC

unknown route

RTN_UNICAST

a gateway or direct route

RTN_LOCAL

a local interface route

RTN_BROADCAST

a local broadcast route (sent as a broadcast)

RTN_ANYCAST

a local broadcast route (sent as a unicast)

RTN_MULTICAST

a multicast route

RTN_BLACKHOLE

a packet dropping route

RTN_UNREACHABLE

an unreachable destination

RTN_PROHIBIT

a packet rejection route

RTN_THROW

continue routing lookup in another table

RTN_NAT

a network address translation rule

RTN_XRESOLVE

refer to an external resolver (not implemented)

rtm_protocol

Route origin

RTPROT_UNSPEC

unknown

RTPROT_REDIRECT

by an ICMP redirect (currently unused)

RTPROT_KERNEL

by the kernel

RTPROT_BOOT

during boot

RTPROT_STATIC

by the administrator

Values larger than RTPROT_STATIC are not interpreted by the kernel, they are just for user information. They may be used to tag the source of a routing information or to distinguish between multiple routing daemons. See <linux/rtnetlink.h> for the routing daemon identifiers which are already assigned.

rtm_scope is the distance to the destination: RT_SCOPE_UNIVERSE

global route

RT_SCOPE_SITE

interior route in the local autonomous system

RT_SCOPE_LINK

route on this link

RT_SCOPE_HOST

route on the local host

RT_SCOPE_NOWHERE

destination doesn't exist

The values between RT_SCOPE_UNIVERSE and RT_SCOPE_SITE are available to the user.

The rtm_flags have the following meanings: RTM_F_NOTIFY

if the route changes, notify the user via rtnetlink

RTM_F_CLONED

route is cloned from another route

RTM_F_EQUALIZE

a multipath equalizer (not yet implemented)

rtm_table specifies the routing table

RT_TABLE_UNSPEC

an unspecified routing table

RT_TABLE_DEFAULT

the default table

RT_TABLE_MAIN

the main table

RT_TABLE_LOCAL

the local table

The user may assign arbitrary values between RT_TABLE_UNSPEC and RT_TABLE_DEFAULT.

Attributes

rta_type

Value type

Description

RTA_UNSPEC

-

ignored

RTA_DST

protocol address

Route destination address

RTA_SRC

protocol address

Route source address

RTA_IIF

int

Input interface index

RTA_OIF

int

Output interface index

RTA_GATEWAY

protocol address

The gateway of the route

RTA_PRIORITY

int

Priority of route

RTA_PREFSRC

protocol address

Preferred source address

RTA_METRICS

int

Route metric

RTA_MULTIPATH

Multipath nexthop data br (see below).

RTA_PROTOINFO

No longer used

RTA_FLOW

int

Route realm

RTA_CACHEINFO

struct rta_cacheinfo

(see linux/rtnetlink.h)

RTA_SESSION

No longer used

RTA_MP_ALGO

No longer used

RTA_TABLE

int

Routing table ID; if set, rtm_table is ignored

RTA_MARK

int

RTA_MFC_STATS

struct rta_mfc_stats

(see linux/rtnetlink.h)

RTA_VIA

struct rtvia

Gateway in different AF (see below)

RTA_NEWDST

protocol address

Change packet destination address

RTA_PREF

char

RFC4191 IPv6 router preference (see below)

RTA_ENCAP_TYPE

short

Encapsulation type for lwtunnels (see below)

RTA_ENCAP

Defined by RTA_ENCAP_TYPE

RTA_EXPIRES

int

Expire time for IPv6 routes (in seconds)

RTA_MULTIPATH contains several packed instances of struct rtnexthop together with nested RTAs (RTA_GATEWAY):

```
struct rtnexthop {

    unsigned short rtnh_len;     /* Length of struct + length

                                    of RTAs */

    unsigned char  rtnh_flags;   /* Flags (see

                                    linux/rtnetlink.h) */

    unsigned char  rtnh_hops;    /* Nexthop priority */

    int            rtnh_ifindex; /* Interface index for this

                                    nexthop */
}

```

There exist a bunch of RTNH_* macros similar to RTA_* and NLHDR_* macros useful to handle these structures.

```
struct rtvia {

    unsigned short rtvia_family;

    unsigned char  rtvia_addr[0];
};

```

rtvia_addr is the address, rtvia_family is its family type.

RTA_PREF may contain values ICMPV6_ROUTER_PREF_LOW, ICMPV6_ROUTER_PREF_MEDIUM, and ICMPV6_ROUTER_PREF_HIGH defined incw <linux/icmpv6.h>.

RTA_ENCAP_TYPE may contain values LWTUNNEL_ENCAP_MPLS, LWTUNNEL_ENCAP_IP, LWTUNNEL_ENCAP_ILA, or LWTUNNEL_ENCAP_IP6 defined in <linux/lwtunnel.h>.

Fill these values in!

RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH

Add, remove, or receive information about a neighbor table entry (e.g., an ARP entry). The message contains an ndmsg structure.

```
struct ndmsg {

    unsigned char ndm_family;

    int           ndm_ifindex;  /* Interface index */

    __u16         ndm_state;    /* State */

    __u8          ndm_flags;    /* Flags */

    __u8          ndm_type;
};
struct nda_cacheinfo {

    __u32         ndm_confirmed;

    __u32         ndm_used;

    __u32         ndm_updated;

    __u32         ndm_refcnt;
};

```

ndm_state is a bit mask of the following states: NUD_INCOMPLETE

a currently resolving cache entry

NUD_REACHABLE

a confirmed working cache entry

NUD_STALE

an expired cache entry

NUD_DELAY

an entry waiting for a timer

NUD_PROBE

a cache entry that is currently reprobed

NUD_FAILED

an invalid cache entry

NUD_NOARP

a device with no destination cache

NUD_PERMANENT

a static entry

Valid ndm_flags are:

NTF_PROXY

a proxy arp entry

NTF_ROUTER

an IPv6 router

The rtattr struct has the following meanings for the rta_type field:

NDA_UNSPEC

unknown type

NDA_DST

a neighbor cache n/w layer destination address

NDA_LLADDR

a neighbor cache link layer address

NDA_CACHEINFO

cache statistics

If the rta_type field is NDA_CACHEINFO, then a struct nda_cacheinfo header follows.

RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE

Add, delete, or retrieve a routing rule. Carries a struct rtmsg

RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC

Add, remove, or get a queueing discipline. The message contains a struct tcmsg and may be followed by a series of attributes.

```
struct tcmsg {

    unsigned char    tcm_family;

    int              tcm_ifindex;   /* interface index */

    __u32            tcm_handle;    /* Qdisc handle */

    __u32            tcm_parent;    /* Parent qdisc */

    __u32            tcm_info;
};

```

Attributes

rta_type

Value type

Description

TCA_UNSPEC

-

unspecified

TCA_KIND

asciiz string

Name of queueing discipline

TCA_OPTIONS

byte sequence

Qdisc-specific options follow

TCA_STATS

struct tc_stats

Qdisc statistics

TCA_XSTATS

qdisc-specific

Module-specific statistics

TCA_RATE

struct tc_estimator

Rate limit

In addition, various other qdisc-module-specific attributes are allowed. For more information see the appropriate include files.

RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS

Add, remove, or get a traffic class. These messages contain a struct tcmsg as described above.

RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER

Add, remove, or receive information about a traffic filter. These messages contain a struct tcmsg as described above.

## VERSIONS
rtnetlink is a new feature of Linux 2.2.

## BUGS
This manual page is incomplete.

## SEE ALSO
cmsg(3), rtnetlink(3), ip(7), netlink(7)


sched

title: sched(7)

summary: overview of CPU scheduling

text:
# sched(7)

## NAME
sched - overview of CPU scheduling

## DESCRIPTION
Since Linux 2.6.23, the default scheduler is CFS, the "Completely Fair Scheduler". The CFS scheduler replaced the earlier "O(1)" scheduler.

### API summary
Linux provides the following system calls for controlling the CPU scheduling behavior, policy, and priority of processes (or, more precisely, threads).

nice(2)

Set a new nice value for the calling thread, and return the new nice value.

getpriority(2)

Return the nice value of a thread, a process group, or the set of threads owned by a specified user.

setpriority(2)

Set the nice value of a thread, a process group, or the set of threads owned by a specified user.

sched_setscheduler(2)

Set the scheduling policy and parameters of a specified thread.

sched_getscheduler(2)

Return the scheduling policy of a specified thread.

sched_setparam(2)

Set the scheduling parameters of a specified thread.

sched_getparam(2)

Fetch the scheduling parameters of a specified thread.

sched_get_priority_max(2)

Return the maximum priority available in a specified scheduling policy.

sched_get_priority_min(2)

Return the minimum priority available in a specified scheduling policy.

sched_rr_get_interval(2)

Fetch the quantum used for threads that are scheduled under the "round-robin" scheduling policy.

sched_yield(2)

Cause the caller to relinquish the CPU, so that some other thread be executed.

sched_setaffinity(2)

(Linux-specific) Set the CPU affinity of a specified thread.

sched_getaffinity(2)

(Linux-specific) Get the CPU affinity of a specified thread.

sched_setattr(2)

Set the scheduling policy and parameters of a specified thread. This (Linux-specific) system call provides a superset of the functionality of sched_setscheduler(2) and sched_setparam(2).

sched_getattr(2)

Fetch the scheduling policy and parameters of a specified thread. This (Linux-specific) system call provides a superset of the functionality of sched_getscheduler(2) and sched_getparam(2).

### Scheduling policies
The scheduler is the kernel component that decides which runnable thread will be executed by the CPU next. Each thread has an associated scheduling policy and a static scheduling priority, sched_priority. The scheduler makes its decisions based on knowledge of the scheduling policy and static priority of all threads on the system.

For threads scheduled under one of the normal scheduling policies (SCHED_OTHER, SCHED_IDLE, SCHED_BATCH), sched_priority is not used in scheduling decisions (it must be specified as 0).

Processes scheduled under one of the real-time policies (SCHED_FIFO, SCHED_RR) have a sched_priority value in the range 1 (low) to 99 (high). (As the numbers imply, real-time threads always have higher priority than normal threads.) Note well: POSIX.1 requires an implementation to support only a minimum 32 distinct priority levels for the real-time policies, and some systems supply just this minimum. Portable programs should use sched_get_priority_min(2) and sched_get_priority_max(2) to find the range of priorities supported for a particular policy.

Conceptually, the scheduler maintains a list of runnable threads for each possible sched_priority value. In order to determine which thread runs next, the scheduler looks for the nonempty list with the highest static priority and selects the thread at the head of this list.

A thread's scheduling policy determines where it will be inserted into the list of threads with equal static priority and how it will move inside this list.

All scheduling is preemptive: if a thread with a higher static priority becomes ready to run, the currently running thread will be preempted and returned to the wait list for its static priority level. The scheduling policy determines the ordering only within the list of runnable threads with equal static priority.

### SCHED_FIFO: First in-first out scheduling
SCHED_FIFO can be used only with static priorities higher than 0, which means that when a SCHED_FIFO thread becomes runnable, it will always immediately preempt any currently running SCHED_OTHER, SCHED_BATCH, or SCHED_IDLE thread. SCHED_FIFO is a simple scheduling algorithm without time slicing. For threads scheduled under the SCHED_FIFO policy, the following rules apply:

1)

A running SCHED_FIFO thread that has been preempted by another thread of higher priority will stay at the head of the list for its priority and will resume execution as soon as all threads of higher priority are blocked again.

2)

When a blocked SCHED_FIFO thread becomes runnable, it will be inserted at the end of the list for its priority.

3)

If a call to sched_setscheduler(2), sched_setparam(2), sched_setattr(2), pthread_setschedparam(3), or pthread_setschedprio(3) changes the priority of the running or runnable SCHED_FIFO thread identified by pid the effect on the thread's position in the list depends on the direction of the change to threads priority:

- If the thread's priority is raised, it is placed at the end of the list for its new priority. As a consequence, it may preempt a currently running thread with the same priority.

- If the thread's priority is unchanged, its position in the run list is unchanged.

- If the thread's priority is lowered, it is placed at the front of the list for its new priority.

According to POSIX.1-2008, changes to a thread's priority (or policy) using any mechanism other than pthread_setschedprio(3) should result in the thread being placed at the end of the list for its priority.

4)

A thread calling sched_yield(2) will be put at the end of the list.

No other events will move a thread scheduled under the SCHED_FIFO policy in the wait list of runnable threads with equal static priority.

A SCHED_FIFO thread runs until either it is blocked by an I/O request, it is preempted by a higher priority thread, or it calls sched_yield(2).

### SCHED_RR: Round-robin scheduling
SCHED_RR is a simple enhancement of SCHED_FIFO. Everything described above for SCHED_FIFO also applies to SCHED_RR, except that each thread is allowed to run only for a maximum time quantum. If a SCHED_RR thread has been running for a time period equal to or longer than the time quantum, it will be put at the end of the list for its priority. A SCHED_RR thread that has been preempted by a higher priority thread and subsequently resumes execution as a running thread will complete the unexpired portion of its round-robin time quantum. The length of the time quantum can be retrieved using sched_rr_get_interval(2).

### SCHED_DEADLINE: Sporadic task model deadline scheduling
Since version 3.14, Linux provides a deadline scheduling policy (SCHED_DEADLINE). This policy is currently implemented using GEDF (Global Earliest Deadline First) in conjunction with CBS (Constant Bandwidth Server). To set and fetch this policy and associated attributes, one must use the Linux-specific sched_setattr(2) and sched_getattr(2) system calls.

A sporadic task is one that has a sequence of jobs, where each job is activated at most once per period. Each job also has a relative deadline, before which it should finish execution, and a computation time, which is the CPU time necessary for executing the job. The moment when a task wakes up because a new job has to be executed is called the arrival time (also referred to as the request time or release time). The start time is the time at which a task starts its execution. The absolute deadline is thus obtained by adding the relative deadline to the arrival time.

The following diagram clarifies these terms:

```
arrival/wakeup                    absolute deadline

     |    start time                    |

     |        |                         |

     v        v                         v
-----x--------xooooooooooooooooo--------x--------x---

              |<- comp. time ->|

     |<------- relative deadline ------>|

     |<-------------- period ------------------->|
```

When setting a SCHED_DEADLINE policy for a thread using sched_setattr(2), one can specify three parameters: Runtime, Deadline, and Period. These parameters do not necessarily correspond to the aforementioned terms: usual practice is to set Runtime to something bigger than the average computation time (or worst-case execution time for hard real-time tasks), Deadline to the relative deadline, and Period to the period of the task. Thus, for SCHED_DEADLINE scheduling, we have:

```
arrival/wakeup                    absolute deadline

     |    start time                    |

     |        |                         |

     v        v                         v
-----x--------xooooooooooooooooo--------x--------x---

              |<-- Runtime ------->|

     |<----------- Deadline ----------->|

     |<-------------- Period ------------------->|
```

The three deadline-scheduling parameters correspond to the sched_runtime, sched_deadline, and sched_period fields of the sched_attr structure; see sched_setattr(2). These fields express values in nanoseconds. If sched_period is specified as 0, then it is made the same as sched_deadline.

The kernel requires that:

sched_runtime <= sched_deadline <= sched_period

In addition, under the current implementation, all of the parameter values must be at least 1024 (i.e., just over one microsecond, which is the resolution of the implementation), and less than 2^63. If any of these checks fails, sched_setattr(2) fails with the error EINVAL.

The CBS guarantees non-interference between tasks, by throttling threads that attempt to over-run their specified Runtime.

To ensure deadline scheduling guarantees, the kernel must prevent situations where the set of SCHED_DEADLINE threads is not feasible (schedulable) within the given constraints. The kernel thus performs an admittance test when setting or changing SCHED_DEADLINE policy and attributes. This admission test calculates whether the change is feasible; if it is not, sched_setattr(2) fails with the error EBUSY.

For example, it is required (but not necessarily sufficient) for the total utilization to be less than or equal to the total number of CPUs available, where, since each thread can maximally run for Runtime per Period, that thread's utilization is its Runtime divided by its Period.

In order to fulfill the guarantees that are made when a thread is admitted to the SCHED_DEADLINE policy, SCHED_DEADLINE threads are the highest priority (user controllable) threads in the system; if any SCHED_DEADLINE thread is runnable, it will preempt any thread scheduled under one of the other policies.

A call to fork(2) by a thread scheduled under the SCHED_DEADLINE policy fails with the error EAGAIN, unless the thread has its reset-on-fork flag set (see below).

A SCHED_DEADLINE thread that calls sched_yield(2) will yield the current job and wait for a new period to begin.

### SCHED_OTHER: Default Linux time-sharing scheduling
SCHED_OTHER can be used at only static priority 0 (i.e., threads under real-time policies always have priority over SCHED_OTHER processes). SCHED_OTHER is the standard Linux time-sharing scheduler that is intended for all threads that do not require the special real-time mechanisms.

The thread to run is chosen from the static priority 0 list based on a dynamic priority that is determined only inside this list. The dynamic priority is based on the nice value (see below) and is increased for each time quantum the thread is ready to run, but denied to run by the scheduler. This ensures fair progress among all SCHED_OTHER threads.

In the Linux kernel source code, the SCHED_OTHER policy is actually named SCHED_NORMAL.

### The nice value
The nice value is an attribute that can be used to influence the CPU scheduler to favor or disfavor a process in scheduling decisions. It affects the scheduling of SCHED_OTHER and SCHED_BATCH (see below) processes. The nice value can be modified using nice(2), setpriority(2), or sched_setattr(2).

According to POSIX.1, the nice value is a per-process attribute; that is, the threads in a process should share a nice value. However, on Linux, the nice value is a per-thread attribute: different threads in the same process may have different nice values.

The range of the nice value varies across UNIX systems. On modern Linux, the range is -20 (high priority) to +19 (low priority). On some other systems, the range is -20..20. Very early Linux kernels (Before Linux 2.0) had the range -infinity..15.

The degree to which the nice value affects the relative scheduling of SCHED_OTHER processes likewise varies across UNIX systems and across Linux kernel versions.

With the advent of the CFS scheduler in kernel 2.6.23, Linux adopted an algorithm that causes relative differences in nice values to have a much stronger effect. In the current implementation, each unit of difference in the nice values of two processes results in a factor of 1.25 in the degree to which the scheduler favors the higher priority process. This causes very low nice values (+19) to truly provide little CPU to a process whenever there is any other higher priority load on the system, and makes high nice values (-20) deliver most of the CPU to applications that require it (e.g., some audio applications).

On Linux, the RLIMIT_NICE resource limit can be used to define a limit to which an unprivileged process's nice value can be raised; see setrlimit(2) for details.

For further details on the nice value, see the subsections on the autogroup feature and group scheduling, below.

### SCHED_BATCH: Scheduling batch processes
(Since Linux 2.6.16.) SCHED_BATCH can be used only at static priority 0. This policy is similar to SCHED_OTHER in that it schedules the thread according to its dynamic priority (based on the nice value). The difference is that this policy will cause the scheduler to always assume that the thread is CPU-intensive. Consequently, the scheduler will apply a small scheduling penalty with respect to wakeup behavior, so that this thread is mildly disfavored in scheduling decisions.

This policy is useful for workloads that are noninteractive, but do not want to lower their nice value, and for workloads that want a deterministic scheduling policy without interactivity causing extra preemptions (between the workload's tasks).

### SCHED_IDLE: Scheduling very low priority jobs
(Since Linux 2.6.23.) SCHED_IDLE can be used only at static priority 0; the process nice value has no influence for this policy.

This policy is intended for running jobs at extremely low priority (lower even than a +19 nice value with the SCHED_OTHER or SCHED_BATCH policies).

### Resetting scheduling policy for child processes
Each thread has a reset-on-fork scheduling flag. When this flag is set, children created by fork(2) do not inherit privileged scheduling policies. The reset-on-fork flag can be set by either:

- ORing the SCHED_RESET_ON_FORK flag into the policy argument when calling sched_setscheduler(2) (since Linux 2.6.32); or

- specifying the SCHED_FLAG_RESET_ON_FORK flag in attr.sched_flags when calling sched_setattr(2).

Note that the constants used with these two APIs have different names. The state of the reset-on-fork flag can analogously be retrieved using sched_getscheduler(2) and sched_getattr(2).

The reset-on-fork feature is intended for media-playback applications, and can be used to prevent applications evading the RLIMIT_RTTIME resource limit (see getrlimit(2)) by creating multiple child processes.

More precisely, if the reset-on-fork flag is set, the following rules apply for subsequently created children:

- If the calling thread has a scheduling policy of SCHED_FIFO or SCHED_RR, the policy is reset to SCHED_OTHER in child processes.

- If the calling process has a negative nice value, the nice value is reset to zero in child processes.

After the reset-on-fork flag has been enabled, it can be reset only if the thread has the CAP_SYS_NICE capability. This flag is disabled in child processes created by fork(2).

### Privileges and resource limits
In Linux kernels before 2.6.12, only privileged (CAP_SYS_NICE) threads can set a nonzero static priority (i.e., set a real-time scheduling policy). The only change that an unprivileged thread can make is to set the SCHED_OTHER policy, and this can be done only if the effective user ID of the caller matches the real or effective user ID of the target thread (i.e., the thread specified by pid) whose policy is being changed.

A thread must be privileged (CAP_SYS_NICE) in order to set or modify a SCHED_DEADLINE policy.

Since Linux 2.6.12, the RLIMIT_RTPRIO resource limit defines a ceiling on an unprivileged thread's static priority for the SCHED_RR and SCHED_FIFO policies. The rules for changing scheduling policy and priority are as follows:

- If an unprivileged thread has a nonzero RLIMIT_RTPRIO soft limit, then it can change its scheduling policy and priority, subject to the restriction that the priority cannot be set to a value higher than the maximum of its current priority and its RLIMIT_RTPRIO soft limit.

- If the RLIMIT_RTPRIO soft limit is 0, then the only permitted changes are to lower the priority, or to switch to a non-real-time policy.

- Subject to the same rules, another unprivileged thread can also make these changes, as long as the effective user ID of the thread making the change matches the real or effective user ID of the target thread.

- Special rules apply for the SCHED_IDLE policy. In Linux kernels before 2.6.39, an unprivileged thread operating under this policy cannot change its policy, regardless of the value of its RLIMIT_RTPRIO resource limit. In Linux kernels since 2.6.39, an unprivileged thread can switch to either the SCHED_BATCH or the SCHED_OTHER policy so long as its nice value falls within the range permitted by its RLIMIT_NICE resource limit (see getrlimit(2)).

Privileged (CAP_SYS_NICE) threads ignore the RLIMIT_RTPRIO limit; as with older kernels, they can make arbitrary changes to scheduling policy and priority. See getrlimit(2) for further information on RLIMIT_RTPRIO.

### Limiting the CPU usage of real-time and deadline processes
A nonblocking infinite loop in a thread scheduled under the SCHED_FIFO, SCHED_RR, or SCHED_DEADLINE policy can potentially block all other threads from accessing the CPU forever. Prior to Linux 2.6.25, the only way of preventing a runaway real-time process from freezing the system was to run (at the console) a shell scheduled under a higher static priority than the tested application. This allows an emergency kill of tested real-time applications that do not block or terminate as expected.

Since Linux 2.6.25, there are other techniques for dealing with runaway real-time and deadline processes. One of these is to use the RLIMIT_RTTIME resource limit to set a ceiling on the CPU time that a real-time process may consume. See getrlimit(2) for details.

Since version 2.6.25, Linux also provides two /proc files that can be used to reserve a certain amount of CPU time to be used by non-real-time processes. Reserving CPU time in this fashion allows some CPU time to be allocated to (say) a root shell that can be used to kill a runaway process. Both of these files specify time values in microseconds:

/proc/sys/kernel/sched_rt_period_us

This file specifies a scheduling period that is equivalent to 100% CPU bandwidth. The value in this file can range from 1 to INT_MAX, giving an operating range of 1 microsecond to around 35 minutes. The default value in this file is 1,000,000 (1 second).

/proc/sys/kernel/sched_rt_runtime_us

The value in this file specifies how much of the "period" time can be used by all real-time and deadline scheduled processes on the system. The value in this file can range from -1 to INT_MAX-1. Specifying -1 makes the run time the same as the period; that is, no CPU time is set aside for non-real-time processes (which was the Linux behavior before kernel 2.6.25). The default value in this file is 950,000 (0.95 seconds), meaning that 5% of the CPU time is reserved for processes that don't run under a real-time or deadline scheduling policy.

### Response time
A blocked high priority thread waiting for I/O has a certain response time before it is scheduled again. The device driver writer can greatly reduce this response time by using a "slow interrupt" interrupt handler.

### Miscellaneous
Child processes inherit the scheduling policy and parameters across a fork(2). The scheduling policy and parameters are preserved across execve(2).

Memory locking is usually needed for real-time processes to avoid paging delays; this can be done with mlock(2) or mlockall(2).

### The autogroup feature
Since Linux 2.6.38, the kernel provides a feature known as autogrouping to improve interactive desktop performance in the face of multiprocess, CPU-intensive workloads such as building the Linux kernel with large numbers of parallel build processes (i.e., the make(1) -j flag).

This feature operates in conjunction with the CFS scheduler and requires a kernel that is configured with CONFIG_SCHED_AUTOGROUP. On a running system, this feature is enabled or disabled via the file /proc/sys/kernel/sched_autogroup_enabled; a value of 0 disables the feature, while a value of 1 enables it. The default value in this file is 1, unless the kernel was booted with the noautogroup parameter.

A new autogroup is created when a new session is created via setsid(2); this happens, for example, when a new terminal window is started. A new process created by fork(2) inherits its parent's autogroup membership. Thus, all of the processes in a session are members of the same autogroup. An autogroup is automatically destroyed when the last process in the group terminates.

When autogrouping is enabled, all of the members of an autogroup are placed in the same kernel scheduler "task group". The CFS scheduler employs an algorithm that equalizes the distribution of CPU cycles across task groups. The benefits of this for interactive desktop performance can be described via the following example.

Suppose that there are two autogroups competing for the same CPU (i.e., presume either a single CPU system or the use of taskset(1) to confine all the processes to the same CPU on an SMP system). The first group contains ten CPU-bound processes from a kernel build started with make -j10. The other contains a single CPU-bound process: a video player. The effect of autogrouping is that the two groups will each receive half of the CPU cycles. That is, the video player will receive 50% of the CPU cycles, rather than just 9% of the cycles, which would likely lead to degraded video playback. The situation on an SMP system is more complex, but the general effect is the same: the scheduler distributes CPU cycles across task groups such that an autogroup that contains a large number of CPU-bound processes does not end up hogging CPU cycles at the expense of the other jobs on the system.

A process's autogroup (task group) membership can be viewed via the file /proc/[pid]/autogroup:

```
$ cat /proc/1/autogroup
/autogroup-1 nice 0
```

This file can also be used to modify the CPU bandwidth allocated to an autogroup. This is done by writing a number in the "nice" range to the file to set the autogroup's nice value. The allowed range is from +19 (low priority) to -20 (high priority). (Writing values outside of this range causes write(2) to fail with the error EINVAL.)

The autogroup nice setting has the same meaning as the process nice value, but applies to distribution of CPU cycles to the autogroup as a whole, based on the relative nice values of other autogroups. For a process inside an autogroup, the CPU cycles that it receives will be a product of the autogroup's nice value (compared to other autogroups) and the process's nice value (compared to other processes in the same autogroup.

The use of the cgroups(7) CPU controller to place processes in cgroups other than the root CPU cgroup overrides the effect of autogrouping.

The autogroup feature groups only processes scheduled under non-real-time policies (SCHED_OTHER, SCHED_BATCH, and SCHED_IDLE). It does not group processes scheduled under real-time and deadline policies. Those processes are scheduled according to the rules described earlier.

### The nice value and group scheduling
When scheduling non-real-time processes (i.e., those scheduled under the SCHED_OTHER, SCHED_BATCH, and SCHED_IDLE policies), the CFS scheduler employs a technique known as "group scheduling", if the kernel was configured with the CONFIG_FAIR_GROUP_SCHED option (which is typical).

Under group scheduling, threads are scheduled in "task groups". Task groups have a hierarchical relationship, rooted under the initial task group on the system, known as the "root task group". Task groups are formed in the following circumstances:

- All of the threads in a CPU cgroup form a task group. The parent of this task group is the task group of the corresponding parent cgroup.

- If autogrouping is enabled, then all of the threads that are (implicitly) placed in an autogroup (i.e., the same session, as created by setsid(2)) form a task group. Each new autogroup is thus a separate task group. The root task group is the parent of all such autogroups.

- If autogrouping is enabled, then the root task group consists of all processes in the root CPU cgroup that were not otherwise implicitly placed into a new autogroup.

- If autogrouping is disabled, then the root task group consists of all processes in the root CPU cgroup.

- If group scheduling was disabled (i.e., the kernel was configured without CONFIG_FAIR_GROUP_SCHED), then all of the processes on the system are notionally placed in a single task group.

Under group scheduling, a thread's nice value has an effect for scheduling decisions only relative to other threads in the same task group. This has some surprising consequences in terms of the traditional semantics of the nice value on UNIX systems. In particular, if autogrouping is enabled (which is the default in various distributions), then employing setpriority(2) or nice(1) on a process has an effect only for scheduling relative to other processes executed in the same session (typically: the same terminal window).

Conversely, for two processes that are (for example) the sole CPU-bound processes in different sessions (e.g., different terminal windows, each of whose jobs are tied to different autogroups), modifying the nice value of the process in one of the sessions has no effect in terms of the scheduler's decisions relative to the process in the other session. A possibly useful workaround here is to use a command such as the following to modify the autogroup nice value for all of the processes in a terminal session:

```
$ echo 10 > /proc/self/autogroup
```

### Real-time features in the mainline Linux kernel
Since kernel version 2.6.18, Linux is gradually becoming equipped with real-time capabilities, most of which are derived from the former realtime-preempt patch set. Until the patches have been completely merged into the mainline kernel, they must be installed to achieve the best real-time performance. These patches are named:

```
patch-kernelversion-rtpatchversion
```

and can be downloaded from http://www.kernel.org/pub/linux/kernel/projects/rt/.

Without the patches and prior to their full inclusion into the mainline kernel, the kernel configuration offers only the three preemption classes CONFIG_PREEMPT_NONE, CONFIG_PREEMPT_VOLUNTARY, and CONFIG_PREEMPT_DESKTOP which respectively provide no, some, and considerable reduction of the worst-case scheduling latency.

With the patches applied or after their full inclusion into the mainline kernel, the additional configuration item CONFIG_PREEMPT_RT becomes available. If this is selected, Linux is transformed into a regular real-time operating system. The FIFO and RR scheduling policies are then used to run a thread with true real-time priority and a minimum worst-case scheduling latency.

## NOTES
The cgroups(7) CPU controller can be used to limit the CPU consumption of groups of processes.

Originally, Standard Linux was intended as a general-purpose operating system being able to handle background processes, interactive applications, and less demanding real-time applications (applications that need to usually meet timing deadlines). Although the Linux kernel 2.6 allowed for kernel preemption and the newly introduced O(1) scheduler ensures that the time needed to schedule is fixed and deterministic irrespective of the number of active tasks, true real-time computing was not possible up to kernel version 2.6.17.

## SEE ALSO
chcpu(1), chrt(1), lscpu(1), ps(1), taskset(1), top(1), getpriority(2), mlock(2), mlockall(2), munlock(2), munlockall(2), nice(2), sched_get_priority_max(2), sched_get_priority_min(2), sched_getaffinity(2), sched_getparam(2), sched_getscheduler(2), sched_rr_get_interval(2), sched_setaffinity(2), sched_setparam(2), sched_setscheduler(2), sched_yield(2), setpriority(2), pthread_getaffinity_np(3), pthread_getschedparam(3), pthread_setaffinity_np(3), sched_getcpu(3), capabilities(7), cpuset(7)

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0.

The Linux kernel source files Documentation/scheduler/sched-deadline.txt, Documentation/scheduler/sched-rt-group.txt, Documentation/scheduler/sched-design-CFS.txt, and Documentation/scheduler/sched-nice-design.txt


title: sem_overview(7)

summary: overview of POSIX semaphores

text:
# sem_overview(7)

## NAME
sem_overview - overview of POSIX semaphores

## DESCRIPTION
POSIX semaphores allow processes and threads to synchronize their actions.

A semaphore is an integer whose value is never allowed to fall below zero. Two operations can be performed on semaphores: increment the semaphore value by one (sem_post(3)); and decrement the semaphore value by one (sem_wait(3)). If the value of a semaphore is currently zero, then a sem_wait(3) operation will block until the value becomes greater than zero.

POSIX semaphores come in two forms: named semaphores and unnamed semaphores.

Named semaphores

A named semaphore is identified by a name of the form /somename; that is, a null-terminated string of up to NAME_MAX-4 (i.e., 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).

The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3). When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore. When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).

Unnamed semaphores (memory-based semaphores)

An unnamed semaphore does not have a name. Instead the semaphore is placed in a region of memory that is shared between multiple threads (a thread-shared semaphore) or processes (a process-shared semaphore). A thread-shared semaphore is placed in an area of memory shared between the threads of a process, for example, a global variable. A process-shared semaphore must be placed in a shared memory region (e.g., a System V shared memory segment created using shmget(2), or a POSIX shared memory object built created using shm_open(3)).

Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required, and before the memory in which it is located is deallocated, the semaphore should be destroyed using sem_destroy(3).

The remainder of this section describes some specific details of the Linux implementation of POSIX semaphores.

### Versions
Prior to kernel 2.6, Linux supported only unnamed, thread-shared semaphores. On a system with Linux 2.6 and a glibc that provides the NPTL threading implementation, a complete implementation of POSIX semaphores is provided.

### Persistence
POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down.

### Linking
Programs using the POSIX semaphores API must be compiled with cc -pthread to link against the real-time library, librt.

### Accessing named semaphores via the filesystem
On Linux, named semaphores are created in a virtual filesystem, normally mounted under /dev/shm, with names of the form sem.somename. (This is the reason that semaphore names are limited to NAME_MAX-4 rather than NAME_MAX characters.)

Since Linux 2.6.19, ACLs can be placed on files under this directory, to control object permissions on a per-user and per-group basis.

## NOTES
System V semaphores (semget(2), semop(2), etc.) are an older semaphore API. POSIX semaphores provide a simpler, and better designed interface than System V semaphores; on the other hand POSIX semaphores are less widely available (especially on older systems) than System V semaphores.

## EXAMPLES
An example of the use of various POSIX semaphore functions is shown in sem_wait(3).

## SEE ALSO
sem_close(3), sem_destroy(3), sem_getvalue(3), sem_init(3), sem_open(3), sem_post(3), sem_unlink(3), sem_wait(3), pthreads(7), shm_overview(7)


session-keyring

title: session-keyring(7)

summary: session shared process keyring

text:
# session-keyring(7)

## NAME
session-keyring - session shared process keyring

## DESCRIPTION
The session keyring is a keyring used to anchor keys on behalf of a process. It is typically created by pam_keyinit(8) when a user logs in and a link will be added that refers to the user-keyring(7). Optionally, PAM may revoke the session keyring on logout. (In typical configurations, PAM does do this revocation.) The session keyring has the name (description) _ses.

A special serial number value, KEY_SPEC_SESSION_KEYRING, is defined that can be used in lieu of the actual serial number of the calling process's session keyring.

From the keyctl(1) utility, '@s' can be used instead of a numeric key ID in much the same way.

A process's session keyring is inherited across clone(2), fork(2), and vfork(2). The session keyring is preserved across execve(2), even when the executable is set-user-ID or set-group-ID or has capabilities. The session keyring is destroyed when the last process that refers to it exits.

If a process doesn't have a session keyring when it is accessed, then, under certain circumstances, the user-session-keyring(7) will be attached as the session keyring and under others a new session keyring will be created. (See user-session-keyring(7) for further details.)

### Special operations
The keyutils library provides the following special operations for manipulating session keyrings:

keyctl_join_session_keyring(3)

This operation allows the caller to change the session keyring that it subscribes to. The caller can join an existing keyring with a specified name (description), create a new keyring with a given name, or ask the kernel to create a new "anonymous" session keyring with the name "_ses". (This function is an interface to the keyctl(2) KEYCTL_JOIN_SESSION_KEYRING operation.)

keyctl_session_to_parent(3)

This operation allows the caller to make the parent process's session keyring to the same as its own. For this to succeed, the parent process must have identical security attributes and must be single threaded. (This function is an interface to the keyctl(2) KEYCTL_SESSION_TO_PARENT operation.)

These operations are also exposed through the keyctl(1) utility as:

```
keyctl session
keyctl session - [<prog> <arg1> <arg2> ...]
keyctl session <name> [<prog> <arg1> <arg2> ...]
```

and:

```
keyctl new_session
```

## SEE ALSO
keyctl(1), keyctl(3), keyctl_join_session_keyring(3), keyctl_session_to_parent(3), keyrings(7), persistent-keyring(7), process-keyring(7), thread-keyring(7), user-keyring(7), user-session-keyring(7), pam_keyinit(8)


title: shm_overview(7)

summary: overview of POSIX shared memory

text:
# shm_overview(7)

## NAME
shm_overview - overview of POSIX shared memory

## DESCRIPTION
The POSIX shared memory API allows processes to communicate information by sharing a region of memory.

The interfaces employed in the API are:

shm_open(3)

Create and open a new object, or open an existing object. This is analogous to open(2). The call returns a file descriptor for use by the other interfaces listed below.

ftruncate(2)

Set the size of the shared memory object. (A newly created shared memory object has a length of zero.)

mmap(2)

Map the shared memory object into the virtual address space of the calling process.

munmap(2)

Unmap the shared memory object from the virtual address space of the calling process.

shm_unlink(3)

Remove a shared memory object name.

close(2)

Close the file descriptor allocated by shm_open(3) when it is no longer needed.

fstat(2)

Obtain a stat structure that describes the shared memory object. Among the information returned by this call are the object's size (st_size), permissions (st_mode), owner (st_uid), and group (st_gid).

fchown(2)

To change the ownership of a shared memory object.

fchmod(2)

To change the permissions of a shared memory object.

### Versions
POSIX shared memory is supported since Linux 2.4 and glibc 2.2.

### Persistence
POSIX shared memory objects have kernel persistence: a shared memory object will exist until the system is shut down, or until all processes have unmapped the object and it has been deleted with shm_unlink(3)

### Linking
Programs using the POSIX shared memory API must be compiled with cc -lrt to link against the real-time library, librt.

### Accessing shared memory objects via the filesystem
On Linux, shared memory objects are created in a (tmpfs(5)) virtual filesystem, normally mounted under /dev/shm. Since kernel 2.6.19, Linux supports the use of access control lists (ACLs) to control the permissions of objects in the virtual filesystem.

## NOTES
Typically, processes must synchronize their access to a shared memory object, using, for example, POSIX semaphores.

System V shared memory (shmget(2), shmop(2), etc.) is an older shared memory API. POSIX shared memory provides a simpler, and better designed interface; on the other hand POSIX shared memory is somewhat less widely available (especially on older systems) than System V shared memory.

## SEE ALSO
fchmod(2), fchown(2), fstat(2), ftruncate(2), memfd_create(2), mmap(2), mprotect(2), munmap(2), shmget(2), shmop(2), shm_open(3), shm_unlink(3), sem_overview(7)


sigevent

title: sigevent(7)

text:
# sigevent(7)

## NAME
sigevent - structure for notification from asynchronous routines

## SYNOPSIS

```
#include <signal.h>
```

```
union sigval {            /* Data passed with notification */

    int     sival_int;    /* Integer value */

    void   *sival_ptr;    /* Pointer value */
};
```

```
struct sigevent {

    int    sigev_notify;  /* Notification method */

    int    sigev_signo;   /* Notification signal */

    union sigval sigev_value;

                          /* Data passed with notification */

    void (*sigev_notify_function)(union sigval);

                          /* Function used for thread

                             notification (SIGEV_THREAD) */

    void  *sigev_notify_attributes;

                          /* Attributes for notification thread

                             (SIGEV_THREAD) */

    pid_t  sigev_notify_thread_id;

                          /* ID of thread to signal

                             (SIGEV_THREAD_ID); Linux-specific */
};
```

## DESCRIPTION
The sigevent structure is used by various APIs to describe the way a process is to be notified about an event (e.g., completion of an asynchronous request, expiration of a timer, or the arrival of a message).

The definition shown in the SYNOPSIS is approximate: some of the fields in the sigevent structure may be defined as part of a union. Programs should employ only those fields relevant to the value specified in sigev_notify.

The sigev_notify field specifies how notification is to be performed. This field can have one of the following values:

SIGEV_NONE

A "null" notification: don't do anything when the event occurs.

SIGEV_SIGNAL

Notify the process by sending the signal specified in sigev_signo.

If the signal is caught with a signal handler that was registered using the sigaction(2) SA_SIGINFO flag, then the following fields are set in the siginfo_t structure that is passed as the second argument of the handler:

si_code

This field is set to a value that depends on the API delivering the notification.

si_signo

This field is set to the signal number (i.e., the same value as in sigev_signo).

si_value

This field is set to the value specified in sigev_value.

Depending on the API, other fields may also be set in the siginfo_t structure.

The same information is also available if the signal is accepted using sigwaitinfo(2).

SIGEV_THREAD

Notify the process by invoking sigev_notify_function "as if" it were the start function of a new thread. (Among the implementation possibilities here are that each timer notification could result in the creation of a new thread, or that a single thread is created to receive all notifications.) The function is invoked with sigev_value as its sole argument. If sigev_notify_attributes is not NULL, it should point to a pthread_attr_t structure that defines attributes for the new thread (see pthread_attr_init(3)).

SIGEV_THREAD_ID (Linux-specific)

Currently used only by POSIX timers; see timer_create(2).

## SEE ALSO
timer_create(2), aio_fsync(3), aio_read(3), aio_write(3), getaddrinfo_a(3), lio_listio(3), mq_notify(3), aio(7), pthreads(7)


signal

title: signal(7)

summary: overview of signals

text:
# signal(7)

## NAME
signal - overview of signals

## DESCRIPTION
Linux supports both POSIX reliable signals (hereinafter "standard signals") and POSIX real-time signals.

### Signal dispositions
Each signal has a current disposition, which determines how the process behaves when it is delivered the signal.

The entries in the "Action" column of the table below specify the default disposition for each signal, as follows:

Term

Default action is to terminate the process.

Ign

Default action is to ignore the signal.

Core

Default action is to terminate the process and dump core (see core(5)).

Stop

Default action is to stop the process.

Cont

Default action is to continue the process if it is currently stopped.

A process can change the disposition of a signal using sigaction(2) or signal(2). (The latter is less portable when establishing a signal handler; see signal(2) for details.) Using these system calls, a process can elect one of the following behaviors to occur on delivery of the signal: perform the default action; ignore the signal; or catch the signal with a signal handler, a programmer-defined function that is automatically invoked when the signal is delivered.

By default, a signal handler is invoked on the normal process stack. It is possible to arrange that the signal handler uses an alternate stack; see sigaltstack(2) for a discussion of how to do this and when it might be useful.

The signal disposition is a per-process attribute: in a multithreaded application, the disposition of a particular signal is the same for all threads.

A child created via fork(2) inherits a copy of its parent's signal dispositions. During an execve(2), the dispositions of handled signals are reset to the default; the dispositions of ignored signals are left unchanged.

### Sending a signal
The following system calls and library functions allow the caller to send a signal:

raise(3)

Sends a signal to the calling thread.

kill(2)

Sends a signal to a specified process, to all members of a specified process group, or to all processes on the system.

pidfd_send_signal(2)

Sends a signal to a process identified by a PID file descriptor.

killpg(3)

Sends a signal to all of the members of a specified process group.

pthread_kill(3)

Sends a signal to a specified POSIX thread in the same process as the caller.

tgkill(2)

Sends a signal to a specified thread within a specific process. (This is the system call used to implement pthread_kill(3).)

sigqueue(3)

Sends a real-time signal with accompanying data to a specified process.

### Waiting for a signal to be caught
The following system calls suspend execution of the calling thread until a signal is caught (or an unhandled signal terminates the process):

pause(2)

Suspends execution until any signal is caught.

sigsuspend(2)

Temporarily changes the signal mask (see below) and suspends execution until one of the unmasked signals is caught.

### Synchronously accepting a signal
Rather than asynchronously catching a signal via a signal handler, it is possible to synchronously accept the signal, that is, to block execution until the signal is delivered, at which point the kernel returns information about the signal to the caller. There are two general ways to do this:

- sigwaitinfo(2), sigtimedwait(2), and sigwait(3) suspend execution until one of the signals in a specified set is delivered. Each of these calls returns information about the delivered signal.

- signalfd(2) returns a file descriptor that can be used to read information about signals that are delivered to the caller. Each read(2) from this file descriptor blocks until one of the signals in the set specified in the signalfd(2) call is delivered to the caller. The buffer returned by read(2) contains a structure describing the signal.

### Signal mask and pending signals
A signal may be blocked, which means that it will not be delivered until it is later unblocked. Between the time when it is generated and when it is delivered a signal is said to be pending.

Each thread in a process has an independent signal mask, which indicates the set of signals that the thread is currently blocking. A thread can manipulate its signal mask using pthread_sigmask(3). In a traditional single-threaded application, sigprocmask(2) can be used to manipulate the signal mask.

A child created via fork(2) inherits a copy of its parent's signal mask; the signal mask is preserved across execve(2).

A signal may be process-directed or thread-directed. A process-directed signal is one that is targeted at (and thus pending for) the process as a whole. A signal may be process-directed because it was generated by the kernel for reasons other than a hardware exception, or because it was sent using kill(2) or sigqueue(3). A thread-directed signal is one that is targeted at a specific thread. A signal may be thread-directed because it was generated as a consequence of executing a specific machine-language instruction that triggered a hardware exception (e.g., SIGSEGV for an invalid memory access, or SIGFPE for a math error), or because it was targeted at a specific thread using interfaces such as tgkill(2) or pthread_kill(3).

A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.

A thread can obtain the set of signals that it currently has pending using sigpending(2). This set will consist of the union of the set of pending process-directed signals and the set of signals pending for the calling thread.

A child created via fork(2) initially has an empty pending signal set; the pending signal set is preserved across an execve(2).

### Execution of signal handlers
Whenever there is a transition from kernel-mode to user-mode execution (e.g., on return from a system call or scheduling of a thread onto the CPU), the kernel checks whether there is a pending unblocked signal for which the process has established a signal handler. If there is such a pending signal, the following steps occur:

1.

The kernel performs the necessary preparatory steps for execution of the signal handler:

a)

The signal is removed from the set of pending signals.

b)

If the signal handler was installed by a call to sigaction(2) that specified the SA_ONSTACK flag and the thread has defined an alternate signal stack (using sigaltstack(2)), then that stack is installed.

c)

Various pieces of signal-related context are saved into a special frame that is created on the stack. The saved information includes:

+

the program counter register (i.e., the address of the next instruction in the main program that should be executed when the signal handler returns);

+

architecture-specific register state required for resuming the interrupted program;

+

the thread's current signal mask;

+

the thread's alternate signal stack settings.

(If the signal handler was installed using the sigaction(2) SA_SIGINFO flag, then the above information is accessible via the ucontext_t object that is pointed to by the third argument of the signal handler.)

d)

Any signals specified in act->sa_mask when registering the handler with sigprocmask(2) are added to the thread's signal mask. The signal being delivered is also added to the signal mask, unless SA_NODEFER was specified when registering the handler. These signals are thus blocked while the handler executes.

2.

The kernel constructs a frame for the signal handler on the stack. The kernel sets the program counter for the thread to point to the first instruction of the signal handler function, and configures the return address for that function to point to a piece of user-space code known as the signal trampoline (described in sigreturn(2)).

3.

The kernel passes control back to user-space, where execution commences at the start of the signal handler function.

4.

When the signal handler returns, control passes to the signal trampoline code.

5.

The signal trampoline calls sigreturn(2), a system call that uses the information in the stack frame created in step 1 to restore the thread to its state before the signal handler was called. The thread's signal mask and alternate signal stack settings are restored as part of this procedure. Upon completion of the call to sigreturn(2), the kernel transfers control back to user space, and the thread recommences execution at the point where it was interrupted by the signal handler.

Note that if the signal handler does not return (e.g., control is transferred out of the handler using siglongjmp(3), or the handler executes a new program with execve(2)), then the final step is not performed. In particular, in such scenarios it is the programmer's responsibility to restore the state of the signal mask (using sigprocmask(2)), if it is desired to unblock the signals that were blocked on entry to the signal handler. (Note that siglongjmp(3) may or may not restore the signal mask, depending on the savesigs value that was specified in the corresponding call to sigsetjmp(3).)

From the kernel's point of view, execution of the signal handler code is exactly the same as the execution of any other user-space code. That is to say, the kernel does not record any special state information indicating that the thread is currently executing inside a signal handler. All necessary state information is maintained in user-space registers and the user-space stack. The depth to which nested signal handlers may be invoked is thus limited only by the user-space stack (and sensible software design!).

### Standard signals
Linux supports the standard signals listed below. The second column of the table indicates which standard (if any) specified the signal: "P1990" indicates that the signal is described in the original POSIX.1-1990 standard; "P2001" indicates that the signal was added in SUSv2 and POSIX.1-2001.

Signal

Standard

Action

Comment

SIGABRT

P1990

Core

Abort signal from abort(3)

SIGALRM

P1990

Term

Timer signal from alarm(2)

SIGBUS

P2001

Core

Bus error (bad memory access)

SIGCHLD

P1990

Ign

Child stopped or terminated

SIGCLD

-

Ign

A synonym for SIGCHLD

SIGCONT

P1990

Cont

Continue if stopped

SIGEMT

-

Term

Emulator trap

SIGFPE

P1990

Core

Floating-point exception

SIGHUP

P1990

Term

Hangup detected on controlling terminal

or death of controlling process

SIGILL

P1990

Core

Illegal Instruction

SIGINFO

-

A synonym for SIGPWR

SIGINT

P1990

Term

Interrupt from keyboard

SIGIO

-

Term

I/O now possible (4.2BSD)

SIGIOT

-

Core

IOT trap. A synonym for SIGABRT

SIGKILL

P1990

Term

Kill signal

SIGLOST

-

Term

File lock lost (unused)

SIGPIPE

P1990

Term

Broken pipe: write to pipe with no

readers; see pipe(7)

SIGPOLL

P2001

Term

Pollable event (Sys V);

synonym for SIGIO

SIGPROF

P2001

Term

Profiling timer expired

SIGPWR

-

Term

Power failure (System V)

SIGQUIT

P1990

Core

Quit from keyboard

SIGSEGV

P1990

Core

Invalid memory reference

SIGSTKFLT

-

Term

Stack fault on coprocessor (unused)

SIGSTOP

P1990

Stop

Stop process

SIGTSTP

P1990

Stop

Stop typed at terminal

SIGSYS

P2001

Core

Bad system call (SVr4);

see also seccomp(2)

SIGTERM

P1990

Term

Termination signal

SIGTRAP

P2001

Core

Trace/breakpoint trap

SIGTTIN

P1990

Stop

Terminal input for background process

SIGTTOU

P1990

Stop

Terminal output for background process

SIGUNUSED

-

Core

Synonymous with SIGSYS

SIGURG

P2001

Ign

Urgent condition on socket (4.2BSD)

SIGUSR1

P1990

Term

User-defined signal 1

SIGUSR2

P1990

Term

User-defined signal 2

SIGVTALRM

P2001

Term

Virtual alarm clock (4.2BSD)

SIGXCPU

P2001

Core

CPU time limit exceeded (4.2BSD);

see setrlimit(2)

SIGXFSZ

P2001

Core

File size limit exceeded (4.2BSD);

see setrlimit(2)

SIGWINCH

-

Ign

Window resize signal (4.3BSD, Sun)

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.

Up to and including Linux 2.2, the default behavior for SIGSYS, SIGXCPU, SIGXFSZ, and (on architectures other than SPARC and MIPS) SIGBUS was to terminate the process (without a core dump). (On some other UNIX systems the default action for SIGXCPU and SIGXFSZ is to terminate the process without a core dump.) Linux 2.4 conforms to the POSIX.1-2001 requirements for these signals, terminating the process with a core dump.

SIGEMT is not specified in POSIX.1-2001, but nevertheless appears on most other UNIX systems, where its default action is typically to terminate the process with a core dump.

SIGPWR (which is not specified in POSIX.1-2001) is typically ignored by default on those other UNIX systems where it appears.

SIGIO (which is not specified in POSIX.1-2001) is ignored by default on several other UNIX systems.

### Queueing and delivery semantics for standard signals
If multiple standard signals are pending for a process, the order in which the signals are delivered is unspecified.

Standard signals do not queue. If multiple instances of a standard signal are generated while that signal is blocked, then only one instance of the signal is marked as pending (and the signal will be delivered just once when it is unblocked). In the case where a standard signal is already pending, the siginfo_t structure (see sigaction(2)) associated with that signal is not overwritten on arrival of subsequent instances of the same signal. Thus, the process will receive the information associated with the first instance of the signal.

### Signal numbering for standard signals
The numeric value for each signal is given in the table below. As shown in the table, many signals have different numeric values on different architectures. The first numeric value in each table row shows the signal number on x86, ARM, and most other architectures; the second value is for Alpha and SPARC; the third is for MIPS; and the last is for PARISC. A dash (-) denotes that a signal is absent on the corresponding architecture.

Signal

x86/ARM

Alpha/

MIPS

PARISC

Notes

most others

SPARC

SIGHUP

1

1

1

1

SIGINT

2

2

2

2

SIGQUIT

3

3

3

3

SIGILL

4

4

4

4

SIGTRAP

5

5

5

5

SIGABRT

6

6

6

6

SIGIOT

6

6

6

6

SIGBUS

7

10

10

10

SIGEMT

-

7

7

-

SIGFPE

8

8

8

8

SIGKILL

9

9

9

9

SIGUSR1

10

30

16

16

SIGSEGV

11

11

11

11

SIGUSR2

12

31

17

17

SIGPIPE

13

13

13

13

SIGALRM

14

14

14

14

SIGTERM

15

15

15

15

SIGSTKFLT

16

-

-

7

SIGCHLD

17

20

18

18

SIGCLD

-

-

18

-

SIGCONT

18

19

25

26

SIGSTOP

19

17

23

24

SIGTSTP

20

18

24

25

SIGTTIN

21

21

26

27

SIGTTOU

22

22

27

28

SIGURG

23

16

21

29

SIGXCPU

24

24

30

12

SIGXFSZ

25

25

31

30

SIGVTALRM

26

26

28

20

SIGPROF

27

27

29

21

SIGWINCH

28

28

20

23

SIGIO

29

23

22

22

SIGPOLL

Same as SIGIO

SIGPWR

30

29/-

19

19

SIGINFO

-

29/-

-

-

SIGLOST

-

-/29

-

-

SIGSYS

31

12

12

31

SIGUNUSED

31

-

-

31

Note the following:

- Where defined, SIGUNUSED is synonymous with SIGSYS. Since glibc 2.26, SIGUNUSED is no longer defined on any architecture.

- Signal 29 is SIGINFO/SIGPWR (synonyms for the same value) on Alpha but SIGLOST on SPARC.

### Real-time signals
Starting with version 2.2, Linux supports real-time signals as originally defined in the POSIX.1b real-time extensions (and now included in POSIX.1-2001). The range of supported real-time signals is defined by the macros SIGRTMIN and SIGRTMAX. POSIX.1-2001 requires that an implementation support at least _POSIX_RTSIG_MAX (8) real-time signals.

The Linux kernel supports a range of 33 different real-time signals, numbered 32 to 64. However, the glibc POSIX threads implementation internally uses two (for NPTL) or three (for LinuxThreads) real-time signals (see pthreads(7)), and adjusts the value of SIGRTMIN suitably (to 34 or 35). Because the range of available real-time signals varies according to the glibc threading implementation (and this variation can occur at run time according to the available kernel and glibc), and indeed the range of real-time signals varies across UNIX systems, programs should never refer to real-time signals using hard-coded numbers, but instead should always refer to real-time signals using the notation SIGRTMIN+n, and include suitable (run-time) checks that SIGRTMIN+n does not exceed SIGRTMAX.

Unlike standard signals, real-time signals have no predefined meanings: the entire set of real-time signals can be used for application-defined purposes.

The default action for an unhandled real-time signal is to terminate the receiving process.

Real-time signals are distinguished by the following:

1.

Multiple instances of real-time signals can be queued. By contrast, if multiple instances of a standard signal are delivered while that signal is currently blocked, then only one instance is queued.

2.

If the signal is sent using sigqueue(3), an accompanying value (either an integer or a pointer) can be sent with the signal. If the receiving process establishes a handler for this signal using the SA_SIGINFO flag to sigaction(2), then it can obtain this data via the si_value field of the siginfo_t structure passed as the second argument to the handler. Furthermore, the si_pid and si_uid fields of this structure can be used to obtain the PID and real user ID of the process sending the signal.

3.

Real-time signals are delivered in a guaranteed order. Multiple real-time signals of the same type are delivered in the order they were sent. If different real-time signals are sent to a process, they are delivered starting with the lowest-numbered signal. (I.e., low-numbered signals have highest priority.) By contrast, if multiple standard signals are pending for a process, the order in which they are delivered is unspecified.

If both standard and real-time signals are pending for a process, POSIX leaves it unspecified which is delivered first. Linux, like many other implementations, gives priority to standard signals in this case.

According to POSIX, an implementation should permit at least _POSIX_SIGQUEUE_MAX (32) real-time signals to be queued to a process. However, Linux does things differently. In kernels up to and including 2.6.7, Linux imposes a system-wide limit on the number of queued real-time signals for all processes. This limit can be viewed and (with privilege) changed via the /proc/sys/kernel/rtsig-max file. A related file, /proc/sys/kernel/rtsig-nr, can be used to find out how many real-time signals are currently queued. In Linux 2.6.8, these /proc interfaces were replaced by the RLIMIT_SIGPENDING resource limit, which specifies a per-user limit for queued signals; see setrlimit(2) for further details.

The addition of real-time signals required the widening of the signal set structure (sigset_t) from 32 to 64 bits. Consequently, various system calls were superseded by new system calls that supported the larger signal sets. The old and new system calls are as follows:

Linux 2.0 and earlier

Linux 2.2 and later

sigaction(2)

rt_sigaction(2)

sigpending(2)

rt_sigpending(2)

sigprocmask(2)

rt_sigprocmask(2)

sigreturn(2)

rt_sigreturn(2)

sigsuspend(2)

rt_sigsuspend(2)

sigtimedwait(2)

rt_sigtimedwait(2)

### Interruption of system calls and library functions by signal handlers
If a signal handler is invoked while a system call or library function call is blocked, then either:

- the call is automatically restarted after the signal handler returns; or

- the call fails with the error EINTR.

Which of these two behaviors occurs depends on the interface and whether or not the signal handler was established using the SA_RESTART flag (see sigaction(2)). The details vary across UNIX systems; below, the details for Linux.

If a blocked call to one of the following interfaces is interrupted by a signal handler, then the call is automatically restarted after the signal handler returns if the SA_RESTART flag was used; otherwise the call fails with the error EINTR:

- read(2), readv(2), write(2), writev(2), and ioctl(2) calls on "slow" devices. A "slow" device is one where the I/O call may block for an indefinite time, for example, a terminal, pipe, or socket. If an I/O call on a slow device has already transferred some data by the time it is interrupted by a signal handler, then the call will return a success status (normally, the number of bytes transferred). Note that a (local) disk is not a slow device according to this definition; I/O operations on disk devices are not interrupted by signals.

- open(2), if it can block (e.g., when opening a FIFO; see fifo(7)).

- wait(2), wait3(2), wait4(2), waitid(2), and waitpid(2).

- Socket interfaces: accept(2), connect(2), recv(2), recvfrom(2), recvmmsg(2), recvmsg(2), send(2), sendto(2), and sendmsg(2), unless a timeout has been set on the socket (see below).

- File locking interfaces: flock(2) and the F_SETLKW and F_OFD_SETLKW operations of fcntl(2)

- POSIX message queue interfaces: mq_receive(3), mq_timedreceive(3), mq_send(3), and mq_timedsend(3).

- futex(2) FUTEX_WAIT (since Linux 2.6.22; beforehand, always failed with EINTR).

- getrandom(2).

- pthread_mutex_lock(3), pthread_cond_wait(3), and related APIs.

- futex(2) FUTEX_WAIT_BITSET.

- POSIX semaphore interfaces: sem_wait(3) and sem_timedwait(3) (since Linux 2.6.22; beforehand, always failed with EINTR).

- read(2) from an inotify(7) file descriptor (since Linux 3.8; beforehand, always failed with EINTR).

The following interfaces are never restarted after being interrupted by a signal handler, regardless of the use of SA_RESTART; they always fail with the error EINTR when interrupted by a signal handler:

- "Input" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): accept(2), recv(2), recvfrom(2), recvmmsg(2) (also with a non-NULL timeout argument), and recvmsg(2).

- "Output" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): connect(2), send(2), sendto(2), and sendmsg(2).

- Interfaces used to wait for signals: pause(2), sigsuspend(2), sigtimedwait(2), and sigwaitinfo(2).

- File descriptor multiplexing interfaces: epoll_wait(2), epoll_pwait(2), poll(2), ppoll(2), select(2), and pselect(2).

- System V IPC interfaces: msgrcv(2), msgsnd(2), semop(2), and semtimedop(2).

- Sleep interfaces: clock_nanosleep(2), nanosleep(2), and usleep(3).

- io_getevents(2).

The sleep(3) function is also never restarted if interrupted by a handler, but gives a success return: the number of seconds remaining to sleep.

In certain circumstances, the seccomp(2) user-space notification feature can lead to restarting of system calls that would otherwise never be restarted by SA_RESTART; for details, see seccomp_unotify(2).

### Interruption of system calls and library functions by stop signals
On Linux, even in the absence of signal handlers, certain blocking interfaces can fail with the error EINTR after the process is stopped by one of the stop signals and then resumed via SIGCONT. This behavior is not sanctioned by POSIX.1, and doesn't occur on other systems.

The Linux interfaces that display this behavior are:

- "Input" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): accept(2), recv(2), recvfrom(2), recvmmsg(2) (also with a non-NULL timeout argument), and recvmsg(2).

- "Output" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): connect(2), send(2), sendto(2), and sendmsg(2), if a send timeout (SO_SNDTIMEO) has been set.

- epoll_wait(2), epoll_pwait(2).

- semop(2), semtimedop(2).

- sigtimedwait(2), sigwaitinfo(2).

- Linux 3.7 and earlier: read(2) from an inotify(7) file descriptor

- Linux 2.6.21 and earlier: futex(2) FUTEX_WAIT, sem_timedwait(3), sem_wait(3).

- Linux 2.6.8 and earlier: msgrcv(2), msgsnd(2).

- Linux 2.4 and earlier: nanosleep(2).

## CONFORMING TO
POSIX.1, except as noted.

## NOTES
For a discussion of async-signal-safe functions, see signal-safety(7).

The /proc/[pid]/task/[tid]/status file contains various fields that show the signals that a thread is blocking (SigBlk), catching (SigCgt), or ignoring (SigIgn). (The set of signals that are caught or ignored will be the same across all threads in a process.) Other fields show the set of pending signals that are directed to the thread (SigPnd) as well as the set of pending signals that are directed to the process as a whole (ShdPnd). The corresponding fields in /proc/[pid]/status show the information for the main thread. See proc(5) for further details.

## BUGS
There are six signals that can be delivered as a consequence of a hardware exception: SIGBUS, SIGEMT, SIGFPE, SIGILL, SIGSEGV, and SIGTRAP. Which of these signals is delivered, for any given hardware exception, is not documented and does not always make sense.

For example, an invalid memory access that causes delivery of SIGSEGV on one CPU architecture may cause delivery of SIGBUS on another architecture, or vice versa.

For another example, using the x86 int instruction with a forbidden argument (any number other than 3 or 128) causes delivery of SIGSEGV, even though SIGILL would make more sense, because of how the CPU reports the forbidden operation to the kernel.

## SEE ALSO
kill(1), clone(2), getrlimit(2), kill(2), pidfd_send_signal(2), restart_syscall(2), rt_sigqueueinfo(2), setitimer(2), setrlimit(2), sgetmask(2), sigaction(2), sigaltstack(2), signal(2), signalfd(2), sigpending(2), sigprocmask(2), sigreturn(2), sigsuspend(2), sigwaitinfo(2), abort(3), bsd_signal(3), killpg(3), longjmp(3), pthread_sigqueue(3), raise(3), sigqueue(3), sigset(3), sigsetops(3), sigvec(3), sigwait(3), strsignal(3), swapcontext(3), sysv_signal(3), core(5), proc(5), nptl(7), pthreads(7), sigevent(7)