setreuid

title: setreuid(2)

text:
# setreuid(2)

## NAME
setreuid, setregid - set real and/or effective user or group ID

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

## SYNOPSIS

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

```
int setreuid(uid_t ruid, uid_t euid);
int setregid(gid_t rgid, gid_t egid);
```

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

setreuid(), setregid():

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

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

## DESCRIPTION
setreuid() sets real and effective user IDs of the calling process.

Supplying a value of -1 for either the real or effective user ID forces the system to leave that ID unchanged.

Unprivileged processes may only set the effective user ID to the real user ID, the effective user ID, or the saved set-user-ID.

Unprivileged users may only set the real user ID to the real user ID or the effective user ID.

If the real user ID is set (i.e., ruid is not -1) or the effective user ID is set to a value not equal to the previous real user ID, the saved set-user-ID will be set to the new effective user ID.

Completely analogously, setregid() sets real and effective group ID's of the calling process, and all of the above holds with "group" instead of "user".

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

Note: there are cases where setreuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from setreuid().

## ERRORS
EAGAIN

The call would change the caller's real UID (i.e., ruid does not match the caller's real UID), but there was a temporary failure allocating the necessary kernel data structures.

EAGAIN

ruid does not match the caller's real UID and this call would bring the number of processes belonging to the real user ID ruid over the caller's RLIMIT_NPROC resource limit. Since Linux 3.1, this error case no longer occurs (but robust applications should check for this error); see the description of EAGAIN in execve(2).

EINVAL

One or more of the target user or group IDs is not valid in this user namespace.

EPERM

The calling process is not privileged (on Linux, does not have the necessary capability in its user namespace: CAP_SETUID in the case of setreuid(), or CAP_SETGID in the case of setregid()) and a change other than (i) swapping the effective user (group) ID with the real user (group) ID, or (ii) setting one to the value of the other or (iii) setting the effective user (group) ID to the value of the saved set-user-ID (saved set-group-ID) was specified.

## VERSIONS
POSIX.1 does not specify all of the UID changes that Linux permits for an unprivileged process. For setreuid(), the effective user ID can be made the same as the real user ID or the saved set-user-ID, and it is unspecified whether unprivileged processes may set the real user ID to the real user ID, the effective user ID, or the saved set-user-ID. For setregid(), the real group ID can be changed to the value of the saved set-group-ID, and the effective group ID can be changed to the value of the real group ID or the saved set-group-ID. The precise details of what ID changes are permitted vary across implementations.

POSIX.1 makes no specification about the effect of these calls on the saved set-user-ID and saved set-group-ID.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, 4.3BSD (first appeared in 4.2BSD).

Setting the effective user (group) ID to the saved set-user-ID (saved set-group-ID) is possible since Linux 1.1.37 (1.1.38).

The original Linux setreuid() and setregid() system calls supported only 16-bit user and group IDs. Subsequently, Linux 2.4 added setreuid32() and setregid32(), supporting 32-bit IDs. The glibc setreuid() and setregid() wrapper functions transparently deal with the variations across kernel versions.

### C library/kernel differences
At the kernel level, user IDs and group IDs are a per-thread attribute. However, POSIX requires that all threads in a process share the same credentials. The NPTL threading implementation handles the POSIX requirements by providing wrapper functions for the various system calls that change process UIDs and GIDs. These wrapper functions (including those for setreuid() and setregid()) employ a signal-based technique to ensure that when one thread changes credentials, all of the other threads in the process also change their credentials. For details, see nptl(7).

## SEE ALSO
getgid(2), getuid(2), seteuid(2), setgid(2), setresuid(2), setuid(2), capabilities(7), credentials(7), user_namespaces(7)


setsid

package: man-pages

title: setsid(2)

text:
# setsid(2)

## NAME
setsid - creates a session and sets the process group ID

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

## SYNOPSIS

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

```
pid_t setsid(void);
```

## DESCRIPTION
setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session (i.e., its session ID is made the same as its process ID). The calling process also becomes the process group leader of a new process group in the session (i.e., its process group ID is made the same as its process ID).

The calling process will be the only process in the new process group and in the new session.

Initially, the new session has no controlling terminal. For details of how a session acquires a controlling terminal, see credentials(7).

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

## ERRORS
EPERM

The process group ID of any process equals the PID of the calling process. Thus, in particular, setsid() fails if the calling process is already a process group leader.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

## NOTES
A child created via fork(2) inherits its parent's session ID. The session ID is preserved across an execve(2).

A process group leader is a process whose process group ID equals its PID. Disallowing a process group leader from calling setsid() prevents the possibility that a process group leader places itself in a new session while other processes in the process group remain in the original session; such a scenario would break the strict two-level hierarchy of sessions and process groups. In order to be sure that setsid() will succeed, call fork(2) and have the parent _exit(2), while the child (which by definition can't be a process group leader) calls setsid().

If a session has a controlling terminal, and the CLOCAL flag for that terminal is not set, and a terminal hangup occurs, then the session leader is sent a SIGHUP signal.

If a process that is a session leader terminates, then a SIGHUP signal is sent to each process in the foreground process group of the controlling terminal.

## SEE ALSO
setsid(1), getsid(2), setpgid(2), setpgrp(2), tcgetsid(3), credentials(7), sched(7)


setuid

title: setuid(2)

summary: set user identity

text:
# setuid(2)

## NAME
setuid - set user identity

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

## SYNOPSIS

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

```
int setuid(uid_t uid);
```

## DESCRIPTION
setuid() sets the effective user ID of the calling process. If the calling process is privileged (more precisely: if the process has the CAP_SETUID capability in its user namespace), the real UID and saved set-user-ID are also set.

Under Linux, setuid() is implemented like the POSIX version with the _POSIX_SAVED_IDS feature. This allows a set-user-ID (other than root) program to drop all of its user privileges, do some un-privileged work, and then reengage the original effective user ID in a secure manner.

If the user is root or the program is set-user-ID-root, special care must be taken: setuid() checks the effective user ID of the caller and if it is the superuser, all process-related user ID's are set to uid. After this has occurred, it is impossible for the program to regain root privileges.

Thus, a set-user-ID-root program wishing to temporarily drop root privileges, assume the identity of an unprivileged user, and then regain root privileges afterward cannot use setuid(). You can accomplish this with seteuid(2).

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

Note: there are cases where setuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from setuid().

## ERRORS
EAGAIN

The call would change the caller's real UID (i.e., uid does not match the caller's real UID), but there was a temporary failure allocating the necessary kernel data structures.

EAGAIN

uid does not match the real user ID of the caller and this call would bring the number of processes belonging to the real user ID uid over the caller's RLIMIT_NPROC resource limit. Since Linux 3.1, this error case no longer occurs (but robust applications should check for this error); see the description of EAGAIN in execve(2).

EINVAL

The user ID specified in uid is not valid in this user namespace.

EPERM

The user is not privileged (Linux: does not have the CAP_SETUID capability in its user namespace) and uid does not match the real UID or saved set-user-ID of the calling process.

## VERSIONS

### C library/kernel differences
At the kernel level, user IDs and group IDs are a per-thread attribute. However, POSIX requires that all threads in a process share the same credentials. The NPTL threading implementation handles the POSIX requirements by providing wrapper functions for the various system calls that change process UIDs and GIDs. These wrapper functions (including the one for setuid()) employ a signal-based technique to ensure that when one thread changes credentials, all of the other threads in the process also change their credentials. For details, see nptl(7).

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

Not quite compatible with the 4.4BSD call, which sets all of the real, saved, and effective user IDs.

The original Linux setuid() system call supported only 16-bit user IDs. Subsequently, Linux 2.4 added setuid32() supporting 32-bit IDs. The glibc setuid() wrapper function transparently deals with the variation across kernel versions.

## NOTES
Linux has the concept of the filesystem user ID, normally equal to the effective user ID. The setuid() call also sets the filesystem user ID of the calling process. See setfsuid(2).

If uid is different from the old effective UID, the process will be forbidden from leaving core dumps.

## SEE ALSO
getuid(2), seteuid(2), setfsuid(2), setreuid(2), capabilities(7), credentials(7), user_namespaces(7)


setup

title: setup(2)

text:
# setup(2)

## NAME
setup - setup devices and filesystems, mount root filesystem

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

## SYNOPSIS

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

```
[[deprecated]] int setup(void);
```

## DESCRIPTION
setup() is called once from within linux/init/main.c. It calls initialization functions for devices and filesystems configured into the kernel and then mounts the root filesystem.

No user process may call setup(). Any user process, even a process with superuser permission, will receive EPERM.

## RETURN VALUE
setup() always returns -1 for a user process.

## ERRORS
EPERM

Always, for a user process.

## STANDARDS
Linux.

## VERSIONS
Removed in Linux 2.1.121.

The calling sequence varied: at some times setup() has had a single argument void *BIOS and at other times a single argument int magic.


setxattr

title: setxattr(2)

summary: set an extended attribute value

text:
# setxattr(2)

## NAME
setxattr, lsetxattr, fsetxattr - set an extended attribute value

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

## SYNOPSIS

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

```
int setxattr(const char *path, const char *name,
              const void value[.size], size_t size, int flags);
int lsetxattr(const char *path, const char *name,
              const void value[.size], size_t size, int flags);
int fsetxattr(int fd, const char *name,
              const void value[.size], size_t size, int flags);
```

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

setxattr() sets the value of the extended attribute identified by name and associated with the given path in the filesystem. The size argument specifies the size (in bytes) of value; a zero-length value is permitted.

lsetxattr() is identical to setxattr(), except in the case of a symbolic link, where the extended attribute is set on the link itself, not the file that it refers to.

fsetxattr() is identical to setxattr(), only the extended attribute is set on the open file referred to by fd (as returned by open(2)) in place of path.

An extended attribute name is a null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode. The value of an extended attribute is a chunk of arbitrary textual or binary data of specified length.

By default (i.e., flags is zero), the extended attribute will be created if it does not exist, or the value will be replaced if the attribute already exists. To modify these semantics, one of the following values can be specified in flags:

XATTR_CREATE

Perform a pure create, which fails if the named attribute exists already.

XATTR_REPLACE

Perform a pure replace operation, which fails if the named attribute does not already exist.

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

## ERRORS
EDQUOT

Disk quota limits meant that there is insufficient space remaining to store the extended attribute.

EEXIST

XATTR_CREATE was specified, and the attribute exists already.

ENODATA

XATTR_REPLACE was specified, and the attribute does not exist.

ENOSPC

There is insufficient space remaining to store the extended attribute.

ENOTSUP

The namespace prefix of name is not valid.

ENOTSUP

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

EPERM

The file is marked immutable or append-only. (See ioctl_iflags(2).)

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

ERANGE

The size of name or value exceeds a filesystem-specific limit.

## STANDARDS
Linux.

## HISTORY
Linux 2.4, glibc 2.3.

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


sgetmask

title: sgetmask(2)

summary: manipulation of signal mask (obsolete)

text:
# sgetmask(2)

## NAME
sgetmask, ssetmask - manipulation of signal mask (obsolete)

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

## SYNOPSIS

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

```
[[deprecated]] long syscall(SYS_sgetmask, void);
[[deprecated]] long syscall(SYS_ssetmask, long newmask);
```

## DESCRIPTION
These system calls are obsolete. Do not use them; use sigprocmask(2) instead.

sgetmask() returns the signal mask of the calling process.

ssetmask() sets the signal mask of the calling process to the value given in newmask. The previous signal mask is returned.

The signal masks dealt with by these two system calls are plain bit masks (unlike the sigset_t used by sigprocmask(2)); use sigmask(3) to create and inspect these masks.

## RETURN VALUE
sgetmask() always successfully returns the signal mask. ssetmask() always succeeds, and returns the previous signal mask.

## ERRORS
These system calls always succeed.

## STANDARDS
Linux.

## HISTORY
Since Linux 3.16, support for these system calls is optional, depending on whether the kernel was built with the CONFIG_SGETMASK_SYSCALL option.

## NOTES
These system calls are unaware of signal numbers greater than 31 (i.e., real-time signals).

These system calls do not exist on x86-64.

It is not possible to block SIGSTOP or SIGKILL.

## SEE ALSO
sigprocmask(2), signal(7)


shmctl

title: shmctl(2)

summary: System V shared memory control

text:
# shmctl(2)

## NAME
shmctl - System V shared memory control

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

## SYNOPSIS

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

```
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
```

## DESCRIPTION
shmctl() performs the control operation specified by cmd on the System V shared memory segment whose identifier is given in shmid.

The buf argument is a pointer to a shmid_ds structure, defined in <sys/shm.h> as follows:

```
struct shmid_ds {

    struct ipc_perm shm_perm;    /* Ownership and permissions */

    size_t          shm_segsz;   /* Size of segment (bytes) */

    time_t          shm_atime;   /* Last attach time */

    time_t          shm_dtime;   /* Last detach time */

    time_t          shm_ctime;   /* Creation time/time of last

                                    modification via shmctl() */

    pid_t           shm_cpid;    /* PID of creator */

    pid_t           shm_lpid;    /* PID of last shmat(2)/shmdt(2) */

    shmatt_t        shm_nattch;  /* No. of current attaches */

    ...
};
```

The fields of the shmid_ds structure are as follows:

shm_perm

This is an ipc_perm structure (see below) that specifies the access permissions on the shared memory segment.

shm_segsz

Size in bytes of the shared memory segment.

shm_atime

Time of the last shmat(2) system call that attached this segment.

shm_dtime

Time of the last shmdt(2) system call that detached tgis segment.

shm_ctime

Time of creation of segment or time of the last shmctl() IPC_SET operation.

shm_cpid

ID of the process that created the shared memory segment.

shm_lpid

ID of the last process that executed a shmat(2) or shmdt(2) system call on this segment.

shm_nattch

Number of processes that have this segment attached.

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

```
struct ipc_perm {

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

    uid_t          uid;      /* Effective UID of owner */

    gid_t          gid;      /* Effective GID of owner */

    uid_t          cuid;     /* Effective UID of creator */

    gid_t          cgid;     /* Effective GID of creator */

    unsigned short mode;     /* Permissions + SHM_DEST and

                                SHM_LOCKED flags */

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

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

0400

Read by user

0200

Write by user

0040

Read by group

0020

Write by group

0004

Read by others

0002

Write by others

Bits 0100, 0010, and 0001 (the execute bits) are unused by the system. (It is not necessary to have execute permission on a segment in order to perform a shmat(2) call with the SHM_EXEC flag.)

Valid values for cmd are:

IPC_STAT

Copy information from the kernel data structure associated with shmid into the shmid_ds structure pointed to by buf. The caller must have read permission on the shared memory segment.

IPC_SET

Write the values of some members of the shmid_ds structure pointed to by buf to the kernel data structure associated with this shared memory segment, updating also its shm_ctime member.

The following fields are updated: shm_perm.uid, shm_perm.gid, and (the least significant 9 bits of) shm_perm.mode.

The effective UID of the calling process must match the owner (shm_perm.uid) or creator (shm_perm.cuid) of the shared memory segment, or the caller must be privileged.

IPC_RMID

Mark the segment to be destroyed. The segment will actually be destroyed only after the last process detaches it (i.e., when the shm_nattch member of the associated structure shmid_ds is zero). The caller must be the owner or creator of the segment, or be privileged. The buf argument is ignored.

If a segment has been marked for destruction, then the (nonstandard) SHM_DEST flag of the shm_perm.mode field in the associated data structure retrieved by IPC_STAT will be set.

The caller must ensure that a segment is eventually destroyed; otherwise its pages that were faulted in will remain in memory or swap.

See also the description of /proc/sys/kernel/shm_rmid_forced in proc(5).

IPC_INFO (Linux-specific)

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

```
struct shminfo {

    unsigned long shmmax; /* Maximum segment size */

    unsigned long shmmin; /* Minimum segment size;

                             always 1 */

    unsigned long shmmni; /* Maximum number of segments */

    unsigned long shmseg; /* Maximum number of segments

                             that a process can attach;

                             unused within kernel */

    unsigned long shmall; /* Maximum number of pages of

                             shared memory, system-wide */
};

```

The shmmni, shmmax, and shmall settings can be changed via /proc files of the same name; see proc(5) for details.

SHM_INFO (Linux-specific)

Return a shm_info structure whose fields contain information about system resources consumed by shared memory. This structure is defined in <sys/shm.h> if the _GNU_SOURCE feature test macro is defined:

```
struct shm_info {

    int           used_ids; /* # of currently existing

                               segments */

    unsigned long shm_tot;  /* Total number of shared

                               memory pages */

    unsigned long shm_rss;  /* # of resident shared

                               memory pages */

    unsigned long shm_swp;  /* # of swapped shared

                               memory pages */

    unsigned long swap_attempts;

                            /* Unused since Linux 2.4 */

    unsigned long swap_successes;

                            /* Unused since Linux 2.4 */
};

```

SHM_STAT (Linux-specific)

Return a shmid_ds structure as for IPC_STAT. However, the shmid argument is not a segment identifier, but instead an index into the kernel's internal array that maintains information about all shared memory segments on the system.

SHM_STAT_ANY (Linux-specific, since Linux 4.17)

Return a shmid_ds structure as for SHM_STAT. However, shm_perm.mode is not checked for read access for shmid, meaning that any user can employ this operation (just as any user may read /proc/sysvipc/shm to obtain the same information).

The caller can prevent or allow swapping of a shared memory segment with the following cmd values:

SHM_LOCK (Linux-specific)

Prevent swapping of the shared memory segment. The caller must fault in any pages that are required to be present after locking is enabled. If a segment has been locked, then the (nonstandard) SHM_LOCKED flag of the shm_perm.mode field in the associated data structure retrieved by IPC_STAT will be set.

SHM_UNLOCK (Linux-specific)

Unlock the segment, allowing it to be swapped out.

Before Linux 2.6.10, only a privileged process could employ SHM_LOCK and SHM_UNLOCK. Since Linux 2.6.10, an unprivileged process can employ these operations if its effective UID matches the owner or creator UID of the segment, and (for SHM_LOCK) the amount of memory to be locked falls within the RLIMIT_MEMLOCK resource limit (see setrlimit(2)).

## RETURN VALUE
A successful IPC_INFO or SHM_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all shared memory segments. (This information can be used with repeated SHM_STAT or SHM_STAT_ANY operations to obtain information about all shared memory segments on the system.) A successful SHM_STAT operation returns the identifier of the shared memory segment whose index was given in shmid. Other operations return 0 on success.

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

## ERRORS
EACCES

IPC_STAT or SHM_STAT is requested and shm_perm.mode does not allow read access for shmid, and the calling process does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

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

EIDRM

shmid points to a removed identifier.

EINVAL

shmid is not a valid identifier, or cmd is not a valid command. Or: for a SHM_STAT or SHM_STAT_ANY operation, the index value specified in shmid referred to an array slot that is currently unused.

ENOMEM

(Since Linux 2.6.9), SHM_LOCK was specified and the size of the to-be-locked segment would mean that the total bytes in locked shared memory segments would exceed the limit for the real user ID of the calling process. This limit is defined by the RLIMIT_MEMLOCK soft resource limit (see setrlimit(2)).

EOVERFLOW

IPC_STAT is attempted, and the GID or UID value is too large to be stored in the structure pointed to by buf.

EPERM

IPC_SET or IPC_RMID is attempted, and the effective user ID of the calling process is not that of the creator (found in shm_perm.cuid), or the owner (found in shm_perm.uid), and the process was not privileged (Linux: did not have the CAP_SYS_ADMIN capability).

Or (before Linux 2.6.9), SHM_LOCK or SHM_UNLOCK was specified, but the process was not privileged (Linux: did not have the CAP_IPC_LOCK capability). (Since Linux 2.6.9, this error can also occur if the RLIMIT_MEMLOCK is 0 and the caller is not privileged.)

## VERSIONS
Linux permits a process to attach (shmat(2)) a shared memory segment that has already been marked for deletion using shmctl(IPC_RMID). This feature is not available on other UNIX implementations; portable applications should avoid relying on it.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

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

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

## SEE ALSO
mlock(2), setrlimit(2), shmget(2), shmop(2), capabilities(7), sysvipc(7)


shmget

title: shmget(2)

text:
# shmget(2)

## NAME
shmget - allocates a System V shared memory segment

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

## SYNOPSIS

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

```
int shmget(key_t key, size_t size, int shmflg);
```

## DESCRIPTION
shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key. It may be used either to obtain the identifier of a previously created shared memory segment (when shmflg is zero and key does not have the value IPC_PRIVATE), or to create a new set.

A new shared memory segment, with size equal to the value of size rounded up to a multiple of PAGE_SIZE, is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no shared memory segment corresponding to key exists, and IPC_CREAT is specified in shmflg.

If shmflg specifies both IPC_CREAT and IPC_EXCL and a shared memory segment already exists for key, then shmget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

The value shmflg is composed of:

IPC_CREAT

Create a new segment. If this flag is not used, then shmget() will find the segment associated with key and check to see if the user has permission to access the segment.

IPC_EXCL

This flag is used with IPC_CREAT to ensure that this call creates the segment. If the segment already exists, the call fails.

SHM_HUGETLB (since Linux 2.6)

Allocate the segment using "huge" pages. See the Linux kernel source file Documentation/admin-guide/mm/hugetlbpage.rst for further information.

SHM_HUGE_2MB, SHM_HUGE_1GB (since Linux 3.8)

Used in conjunction with SHM_HUGETLB to select alternative hugetlb page sizes (respectively, 2 MB and 1 GB) on systems that support multiple hugetlb page sizes.

More generally, the desired huge page size can be configured by encoding the base-2 logarithm of the desired page size in the six bits at the offset SHM_HUGE_SHIFT. Thus, the above two constants are defined as:

```
#define SHM_HUGE_2MB    (21 << SHM_HUGE_SHIFT)
#define SHM_HUGE_1GB    (30 << SHM_HUGE_SHIFT)

```

For some additional details, see the discussion of the similarly named constants in mmap(2).

SHM_NORESERVE (since Linux 2.6.15)

This flag serves the same purpose as the mmap(2) MAP_NORESERVE flag. Do not reserve swap space for this segment. When swap space is reserved, one has the guarantee that it is possible to modify the segment. When swap space is not reserved one might get SIGSEGV upon a write if no physical memory is available. See also the discussion of the file /proc/sys/vm/overcommit_memory in proc(5).

In addition to the above flags, the least significant 9 bits of shmflg specify the permissions granted to the owner, group, and others. These bits have the same format, and the same meaning, as the mode argument of open(2). Presently, execute permissions are not used by the system.

When a new shared memory segment is created, its contents are initialized to zero values, and its associated data structure, shmid_ds (see shmctl(2)), is initialized as follows:

•

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

•

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

•

The least significant 9 bits of shm_perm.mode are set to the least significant 9 bit of shmflg.

•

shm_segsz is set to the value of size.

•

shm_lpid, shm_nattch, shm_atime, and shm_dtime are set to 0.

•

shm_ctime is set to the current time.

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

## RETURN VALUE
On success, a valid shared memory identifier is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

The user does not have permission to access the shared memory segment, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EEXIST

IPC_CREAT and IPC_EXCL were specified in shmflg, but a shared memory segment already exists for key.

EINVAL

A new segment was to be created and size is less than SHMMIN or greater than SHMMAX.

EINVAL

A segment for the given key exists, but size is greater than the size of that segment.

ENFILE

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

ENOENT

No segment exists for the given key, and IPC_CREAT was not specified.

ENOMEM

No memory could be allocated for segment overhead.

ENOSPC

All possible shared memory IDs have been taken (SHMMNI), or allocating a segment of the requested size would cause the system to exceed the system-wide limit on shared memory (SHMALL).

EPERM

The SHM_HUGETLB flag was specified, but the caller was not privileged (did not have the CAP_IPC_LOCK capability) and is not a member of the sysctl_hugetlb_shm_group group; see the description of /proc/sys/vm/sysctl_hugetlb_shm_group in proc(5).

## STANDARDS
POSIX.1-2008.

SHM_HUGETLB and SHM_NORESERVE are Linux extensions.

## HISTORY
POSIX.1-2001, SVr4.

## NOTES
IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores all but the least significant 9 bits of shmflg and creates a new shared memory segment.

### Shared memory limits
The following limits on shared memory segment resources affect the shmget() call:

SHMALL

System-wide limit on the total amount of shared memory, measured in units of the system page size.

On Linux, this limit can be read and modified via /proc/sys/kernel/shmall. Since Linux 3.16, the default value for this limit is:

```
ULONG_MAX - 2^24

```

The effect of this value (which is suitable for both 32-bit and 64-bit systems) is to impose no limitation on allocations. This value, rather than ULONG_MAX, was chosen as the default to prevent some cases where historical applications simply raised the existing limit without first checking its current value. Such applications would cause the value to overflow if the limit was set at ULONG_MAX.

From Linux 2.4 up to Linux 3.15, the default value for this limit was:

```
SHMMAX / PAGE_SIZE * (SHMMNI / 16)

```

If SHMMAX and SHMMNI were not modified, then multiplying the result of this formula by the page size (to get a value in bytes) yielded a value of 8 GB as the limit on the total memory used by all shared memory segments.

SHMMAX

Maximum size in bytes for a shared memory segment.

On Linux, this limit can be read and modified via /proc/sys/kernel/shmmax. Since Linux 3.16, the default value for this limit is:

```
ULONG_MAX - 2^24

```

The effect of this value (which is suitable for both 32-bit and 64-bit systems) is to impose no limitation on allocations. See the description of SHMALL for a discussion of why this default value (rather than ULONG_MAX) is used.

From Linux 2.2 up to Linux 3.15, the default value of this limit was 0x2000000 (32 MiB).

Because it is not possible to map just part of a shared memory segment, the amount of virtual memory places another limit on the maximum size of a usable segment: for example, on i386 the largest segments that can be mapped have a size of around 2.8 GB, and on x86-64 the limit is around 127 TB.

SHMMIN

Minimum size in bytes for a shared memory segment: implementation dependent (currently 1 byte, though PAGE_SIZE is the effective minimum size).

SHMMNI

System-wide limit on the number of shared memory segments. In Linux 2.2, the default value for this limit was 128; since Linux 2.4, the default value is 4096.

On Linux, this limit can be read and modified via /proc/sys/kernel/shmmni.

The implementation has no specific limits for the per-process maximum number of shared memory segments (SHMSEG).

### Linux notes
Until Linux 2.3.30, Linux would return EIDRM for a shmget() on a shared memory segment scheduled for deletion.

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

## EXAMPLES
See shmop(2).

## SEE ALSO
memfd_create(2), shmat(2), shmctl(2), shmdt(2), ftok(3), capabilities(7), shm_overview(7), sysvipc(7)


shmop

title: shmop(2)

summary: System V shared memory operations

text:
# shmop(2)

## NAME
shmat, shmdt - System V shared memory operations

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

## SYNOPSIS

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

```
void *shmat(int shmid, const void *_Nullable shmaddr, int shmflg);
int shmdt(const void *shmaddr);
```

## DESCRIPTION

### shmat()
shmat() attaches the System V shared memory segment identified by shmid to the address space of the calling process. The attaching address is specified by shmaddr with one of the following criteria:

•

If shmaddr is NULL, the system chooses a suitable (unused) page-aligned address to attach the segment.

•

If shmaddr isn't NULL and SHM_RND is specified in shmflg, the attach occurs at the address equal to shmaddr rounded down to the nearest multiple of SHMLBA.

•

Otherwise, shmaddr must be a page-aligned address at which the attach occurs.

In addition to SHM_RND, the following flags may be specified in the shmflg bit-mask argument:

SHM_EXEC (Linux-specific; since Linux 2.6.9)

Allow the contents of the segment to be executed. The caller must have execute permission on the segment.

SHM_RDONLY

Attach the segment for read-only access. The process must have read permission for the segment. If this flag is not specified, the segment is attached for read and write access, and the process must have read and write permission for the segment. There is no notion of a write-only shared memory segment.

SHM_REMAP (Linux-specific)

This flag specifies that the mapping of the segment should replace any existing mapping in the range starting at shmaddr and continuing for the size of the segment. (Normally, an EINVAL error would result if a mapping already exists in this address range.) In this case, shmaddr must not be NULL.

The brk(2) value of the calling process is not altered by the attach. The segment will automatically be detached at process exit. The same segment may be attached as a read and as a read-write one, and more than once, in the process's address space.

A successful shmat() call updates the members of the shmid_ds structure (see shmctl(2)) associated with the shared memory segment as follows:

•

shm_atime is set to the current time.

•

shm_lpid is set to the process-ID of the calling process.

•

shm_nattch is incremented by one.

### shmdt()
shmdt() detaches the shared memory segment located at the address specified by shmaddr from the address space of the calling process. The to-be-detached segment must be currently attached with shmaddr equal to the value returned by the attaching shmat() call.

On a successful shmdt() call, the system updates the members of the shmid_ds structure associated with the shared memory segment as follows:

•

shm_dtime is set to the current time.

•

shm_lpid is set to the process-ID of the calling process.

•

shm_nattch is decremented by one. If it becomes 0 and the segment is marked for deletion, the segment is deleted.

## RETURN VALUE
On success, shmat() returns the address of the attached shared memory segment; on error, (void *) -1 is returned, and errno is set to indicate the error.

On success, shmdt() returns 0; on error -1 is returned, and errno is set to indicate the error.

## ERRORS
shmat() can fail with one of the following errors:

EACCES

The calling process does not have the required permissions for the requested attach type, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EIDRM

shmid points to a removed identifier.

EINVAL

Invalid shmid value, unaligned (i.e., not page-aligned and SHM_RND was not specified) or invalid shmaddr value, or can't attach segment at shmaddr, or SHM_REMAP was specified and shmaddr was NULL.

ENOMEM

Could not allocate memory for the descriptor or for the page tables.

shmdt() can fail with one of the following errors:

EINVAL

There is no shared memory segment attached at shmaddr; or, shmaddr is not aligned on a page boundary.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

In SVID 3 (or perhaps earlier), the type of the shmaddr argument was changed from char * into const void *, and the returned type of shmat() from char * into void *.

## NOTES
After a fork(2), the child inherits the attached shared memory segments.

After an execve(2), all attached shared memory segments are detached from the process.

Upon _exit(2), all attached shared memory segments are detached from the process.

Using shmat() with shmaddr equal to NULL is the preferred, portable way of attaching a shared memory segment. Be aware that the shared memory segment attached in this way may be attached at different addresses in different processes. Therefore, any pointers maintained within the shared memory must be made relative (typically to the starting address of the segment), rather than absolute.

On Linux, it is possible to attach a shared memory segment even if it is already marked to be deleted. However, POSIX.1 does not specify this behavior and many other implementations do not support it.

The following system parameter affects shmat():

SHMLBA

Segment low boundary address multiple. When explicitly specifying an attach address in a call to shmat(), the caller should ensure that the address is a multiple of this value. This is necessary on some architectures, in order either to ensure good CPU cache performance or to ensure that different attaches of the same segment have consistent views within the CPU cache. SHMLBA is normally some multiple of the system page size. (On many Linux architectures, SHMLBA is the same as the system page size.)

The implementation places no intrinsic per-process limit on the number of shared memory segments (SHMSEG).

## EXAMPLES
The two programs shown below exchange a string using a shared memory segment. Further details about the programs are given below. First, we show a shell session demonstrating their use.

In one terminal window, we run the "reader" program, which creates a System V shared memory segment and a System V semaphore set. The program prints out the IDs of the created objects, and then waits for the semaphore to change value.

```
$ ./svshm_string_read
shmid = 1114194; semid = 15
```

In another terminal window, we run the "writer" program. The "writer" program takes three command-line arguments: the IDs of the shared memory segment and semaphore set created by the "reader", and a string. It attaches the existing shared memory segment, copies the string to the shared memory, and modifies the semaphore value.

```
$ ./svshm_string_write 1114194 15 'Hello, world'
```

Returning to the terminal where the "reader" is running, we see that the program has ceased waiting on the semaphore and has printed the string that was copied into the shared memory segment by the writer:

```
Hello, world
```

### Program source: svshm_string.h
The following header file is included by the "reader" and "writer" programs:

```
/* svshm_string.h

   Licensed under GNU General Public License v2 or later.
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \

                        } while (0)
union semun {                   /* Used in calls to semctl() */

    int                 val;

    struct semid_ds *   buf;

    unsigned short *    array;
#if defined(__linux__)

    struct seminfo *    __buf;
#endif
};
#define MEM_SIZE 4096
```

### Program source: svshm_string_read.c
The "reader" program creates a shared memory segment and a semaphore set containing one semaphore. It then attaches the shared memory object into its address space and initializes the semaphore value to 1. Finally, the program waits for the semaphore value to become 0, and afterwards prints the string that has been copied into the shared memory segment by the "writer".

```
/* svshm_string_read.c

   Licensed under GNU General Public License v2 or later.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include "svshm_string.h"
int
main(void)
{

    int            semid, shmid;

    char           *addr;

    union semun    arg, dummy;

    struct sembuf  sop;

    /* Create shared memory and semaphore set containing one

       semaphore. */

    shmid = shmget(IPC_PRIVATE, MEM_SIZE, IPC_CREAT | 0600);

    if (shmid == -1)

        errExit("shmget");

    semid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600);

    if (semid == -1)

        errExit("semget");

    /* Attach shared memory into our address space. */

    addr = shmat(shmid, NULL, SHM_RDONLY);

    if (addr == (void *) -1)

        errExit("shmat");

    /* Initialize semaphore 0 in set with value 1. */

    arg.val = 1;

    if (semctl(semid, 0, SETVAL, arg) == -1)

        errExit("semctl");

    printf("shmid = %d; semid = %d\n", shmid, semid);

    /* Wait for semaphore value to become 0. */

    sop.sem_num = 0;

    sop.sem_op = 0;

    sop.sem_flg = 0;

    if (semop(semid, &sop, 1) == -1)

        errExit("semop");

    /* Print the string from shared memory. */

    printf("%s\n", addr);

    /* Remove shared memory and semaphore set. */

    if (shmctl(shmid, IPC_RMID, NULL) == -1)

        errExit("shmctl");

    if (semctl(semid, 0, IPC_RMID, dummy) == -1)

        errExit("semctl");

    exit(EXIT_SUCCESS);
}
```

### Program source: svshm_string_write.c
The writer program takes three command-line arguments: the IDs of the shared memory segment and semaphore set that have already been created by the "reader", and a string. It attaches the shared memory segment into its address space, and then decrements the semaphore value to 0 in order to inform the "reader" that it can now examine the contents of the shared memory.

```
/* svshm_string_write.c

   Licensed under GNU General Public License v2 or later.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include "svshm_string.h"
int
main(int argc, char *argv[])
{

    int            semid, shmid;

    char           *addr;

    size_t         len;

    struct sembuf  sop;

    if (argc != 4) {

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

        exit(EXIT_FAILURE);

    }

    len = strlen(argv[3]) + 1;  /* +1 to include trailing '\0' */

    if (len > MEM_SIZE) {

        fprintf(stderr, "String is too big!\n");

        exit(EXIT_FAILURE);

    }

    /* Get object IDs from command-line. */

    shmid = atoi(argv[1]);

    semid = atoi(argv[2]);

    /* Attach shared memory into our address space and copy string

       (including trailing null byte) into memory. */

    addr = shmat(shmid, NULL, 0);

    if (addr == (void *) -1)

        errExit("shmat");

    memcpy(addr, argv[3], len);

    /* Decrement semaphore to 0. */

    sop.sem_num = 0;

    sop.sem_op = -1;

    sop.sem_flg = 0;

    if (semop(semid, &sop, 1) == -1)

        errExit("semop");

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
brk(2), mmap(2), shmctl(2), shmget(2), capabilities(7), shm_overview(7), sysvipc(7)


shutdown

title: shutdown(2)

text:
# shutdown(2)

## NAME
shutdown - shut down part of a full-duplex connection

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

## SYNOPSIS

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

```
int shutdown(int sockfd, int how);
```

## DESCRIPTION
The shutdown() call causes all or part of a full-duplex connection on the socket associated with sockfd to be shut down. If how is SHUT_RD, further receptions will be disallowed. If how is SHUT_WR, further transmissions will be disallowed. If how is SHUT_RDWR, further receptions and transmissions will be disallowed.

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

## ERRORS
EBADF

sockfd is not a valid file descriptor.

EINVAL

An invalid value was specified in how (but see BUGS).

ENOTCONN

The specified socket is not connected.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, 4.4BSD (first appeared in 4.2BSD).

## NOTES
The constants SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2, respectively, and are defined in <sys/socket.h> since glibc-2.1.91.

## BUGS
Checks for the validity of how are done in domain-specific code, and before Linux 3.7 not all domains performed these checks. Most notably, UNIX domain sockets simply ignored invalid values. This problem was fixed for UNIX domain sockets in Linux 3.7.

## SEE ALSO
close(2), connect(2), socket(2), socket(7)


sigaction

title: sigaction(2)

summary: examine and change a signal action

text:
# sigaction(2)

## NAME
sigaction, rt_sigaction - examine and change a signal action

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

## SYNOPSIS

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

```
int sigaction(int signum,
              const struct sigaction *_Nullable restrict act,
              struct sigaction *_Nullable restrict oldact);
```

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

sigaction():

```
    _POSIX_C_SOURCE
```

siginfo_t:

```
    _POSIX_C_SOURCE >= 199309L
```

## DESCRIPTION
The sigaction() system call is used to change the action taken by a process on receipt of a specific signal. (See signal(7) for an overview of signals.)

signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP.

If act is non-NULL, the new action for signal signum is installed from act. If oldact is non-NULL, the previous action is saved in oldact.

The sigaction structure is defined as something like:

```
struct sigaction {

    void     (*sa_handler)(int);

    void     (*sa_sigaction)(int, siginfo_t *, void *);

    sigset_t   sa_mask;

    int        sa_flags;

    void     (*sa_restorer)(void);
};
```

On some architectures a union is involved: do not assign to both sa_handler and sa_sigaction.

The sa_restorer field is not intended for application use. (POSIX does not specify a sa_restorer field.) Some further details of the purpose of this field can be found in sigreturn(2).

sa_handler specifies the action to be associated with signum and can be one of the following:

•

SIG_DFL for the default action.

•

SIG_IGN to ignore this signal.

•

A pointer to a signal handling function. This function receives the signal number as its only argument.

If SA_SIGINFO is specified in sa_flags, then sa_sigaction (instead of sa_handler) specifies the signal-handling function for signum. This function receives three arguments, as described below.

sa_mask specifies a mask of signals which should be blocked (i.e., added to the signal mask of the thread in which the signal handler is invoked) during execution of the signal handler. In addition, the signal which triggered the handler will be blocked, unless the SA_NODEFER flag is used.

sa_flags specifies a set of flags which modify the behavior of the signal. It is formed by the bitwise OR of zero or more of the following:

SA_NOCLDSTOP

If signum is SIGCHLD, do not receive notification when child processes stop (i.e., when they receive one of SIGSTOP, SIGTSTP, SIGTTIN, or SIGTTOU) or resume (i.e., they receive SIGCONT) (see wait(2)). This flag is meaningful only when establishing a handler for SIGCHLD.

SA_NOCLDWAIT (since Linux 2.6)

If signum is SIGCHLD, do not transform children into zombies when they terminate. See also waitpid(2). This flag is meaningful only when establishing a handler for SIGCHLD, or when setting that signal's disposition to SIG_DFL.

If the SA_NOCLDWAIT flag is set when establishing a handler for SIGCHLD, POSIX.1 leaves it unspecified whether a SIGCHLD signal is generated when a child process terminates. On Linux, a SIGCHLD signal is generated in this case; on some other implementations, it is not.

SA_NODEFER

Do not add the signal to the thread's signal mask while the handler is executing, unless the signal is specified in act.sa_mask. Consequently, a further instance of the signal may be delivered to the thread while it is executing the handler. This flag is meaningful only when establishing a signal handler.

SA_NOMASK is an obsolete, nonstandard synonym for this flag.

SA_ONSTACK

Call the signal handler on an alternate signal stack provided by sigaltstack(2). If an alternate stack is not available, the default stack will be used. This flag is meaningful only when establishing a signal handler.

SA_RESETHAND

Restore the signal action to the default upon entry to the signal handler. This flag is meaningful only when establishing a signal handler.

SA_ONESHOT is an obsolete, nonstandard synonym for this flag.

SA_RESTART

Provide behavior compatible with BSD signal semantics by making certain system calls restartable across signals. This flag is meaningful only when establishing a signal handler. See signal(7) for a discussion of system call restarting.

SA_RESTORER

Not intended for application use. This flag is used by C libraries to indicate that the sa_restorer field contains the address of a "signal trampoline". See sigreturn(2) for more details.

SA_SIGINFO (since Linux 2.2)

The signal handler takes three arguments, not one. In this case, sa_sigaction should be set instead of sa_handler. This flag is meaningful only when establishing a signal handler.

SA_UNSUPPORTED (since Linux 5.11)

Used to dynamically probe for flag bit support.

If an attempt to register a handler succeeds with this flag set in act->sa_flags alongside other flags that are potentially unsupported by the kernel, and an immediately subsequent sigaction() call specifying the same signal number and with a non-NULL oldact argument yields SA_UNSUPPORTED clear in oldact->sa_flags, then oldact->sa_flags may be used as a bitmask describing which of the potentially unsupported flags are, in fact, supported. See the section "Dynamically probing for flag bit support" below for more details.

SA_EXPOSE_TAGBITS (since Linux 5.11)

Normally, when delivering a signal, an architecture-specific set of tag bits are cleared from the si_addr field of siginfo_t. If this flag is set, an architecture-specific subset of the tag bits will be preserved in si_addr.

Programs that need to be compatible with Linux versions older than 5.11 must use SA_UNSUPPORTED to probe for support.

### The siginfo_t argument to a SA_SIGINFO handler
When the SA_SIGINFO flag is specified in act.sa_flags, the signal handler address is passed via the act.sa_sigaction field. This handler takes three arguments, as follows:

```
void
handler(int sig, siginfo_t *info, void *ucontext)
{

    ...
}
```

These three arguments are as follows

sig

The number of the signal that caused invocation of the handler.

info

A pointer to a siginfo_t, which is a structure containing further information about the signal, as described below.

ucontext

This is a pointer to a ucontext_t structure, cast to void *. The structure pointed to by this field contains signal context information that was saved on the user-space stack by the kernel; for details, see sigreturn(2). Further information about the ucontext_t structure can be found in getcontext(3) and signal(7). Commonly, the handler function doesn't make any use of the third argument.

The siginfo_t data type is a structure with the following fields:

```
siginfo_t {

    int      si_signo;     /* Signal number */

    int      si_errno;     /* An errno value */

    int      si_code;      /* Signal code */

    int      si_trapno;    /* Trap number that caused

                              hardware-generated signal

                              (unused on most architectures) */

    pid_t    si_pid;       /* Sending process ID */

    uid_t    si_uid;       /* Real user ID of sending process */

    int      si_status;    /* Exit value or signal */

    clock_t  si_utime;     /* User time consumed */

    clock_t  si_stime;     /* System time consumed */

    union sigval si_value; /* Signal value */

    int      si_int;       /* POSIX.1b signal */

    void    *si_ptr;       /* POSIX.1b signal */

    int      si_overrun;   /* Timer overrun count;

                              POSIX.1b timers */

    int      si_timerid;   /* Timer ID; POSIX.1b timers */

    void    *si_addr;      /* Memory location which caused fault */

    long     si_band;      /* Band event (was int in

                              glibc 2.3.2 and earlier) */

    int      si_fd;        /* File descriptor */

    short    si_addr_lsb;  /* Least significant bit of address

                              (since Linux 2.6.32) */

    void    *si_lower;     /* Lower bound when address violation

                              occurred (since Linux 3.19) */

    void    *si_upper;     /* Upper bound when address violation

                              occurred (since Linux 3.19) */

    int      si_pkey;      /* Protection key on PTE that caused

                              fault (since Linux 4.6) */

    void    *si_call_addr; /* Address of system call instruction

                              (since Linux 3.5) */

    int      si_syscall;   /* Number of attempted system call

                              (since Linux 3.5) */

    unsigned int si_arch;  /* Architecture of attempted system call

                              (since Linux 3.5) */
}
```

si_signo, si_errno and si_code are defined for all signals. (si_errno is generally unused on Linux.) The rest of the struct may be a union, so that one should read only the fields that are meaningful for the given signal:

•

Signals sent with kill(2) and sigqueue(3) fill in si_pid and si_uid. In addition, signals sent with sigqueue(3) fill in si_int and si_ptr with the values specified by the sender of the signal; see sigqueue(3) for more details.

•

Signals sent by POSIX.1b timers (since Linux 2.6) fill in si_overrun and si_timerid. The si_timerid field is an internal ID used by the kernel to identify the timer; it is not the same as the timer ID returned by timer_create(2). The si_overrun field is the timer overrun count; this is the same information as is obtained by a call to timer_getoverrun(2). These fields are nonstandard Linux extensions.

•

Signals sent for message queue notification (see the description of SIGEV_SIGNAL in mq_notify(3)) fill in si_int/si_ptr, with the sigev_value supplied to mq_notify(3); si_pid, with the process ID of the message sender; and si_uid, with the real user ID of the message sender.

•

SIGCHLD fills in si_pid, si_uid, si_status, si_utime, and si_stime, providing information about the child. The si_pid field is the process ID of the child; si_uid is the child's real user ID. The si_status field contains the exit status of the child (if si_code is CLD_EXITED), or the signal number that caused the process to change state. The si_utime and si_stime contain the user and system CPU time used by the child process; these fields do not include the times used by waited-for children (unlike getrusage(2) and times(2)). Up to Linux 2.6, and since Linux 2.6.27, these fields report CPU time in units of sysconf(_SC_CLK_TCK). In Linux 2.6 kernels before Linux 2.6.27, a bug meant that these fields reported time in units of the (configurable) system jiffy (see time(7)).

•

SIGILL, SIGFPE, SIGSEGV, SIGBUS, and SIGTRAP fill in si_addr with the address of the fault. On some architectures, these signals also fill in the si_trapno field.

Some suberrors of SIGBUS, in particular BUS_MCEERR_AO and BUS_MCEERR_AR, also fill in si_addr_lsb. This field indicates the least significant bit of the reported address and therefore the extent of the corruption. For example, if a full page was corrupted, si_addr_lsb contains log2(sysconf(_SC_PAGESIZE)). When SIGTRAP is delivered in response to a ptrace(2) event (PTRACE_EVENT_foo), si_addr is not populated, but si_pid and si_uid are populated with the respective process ID and user ID responsible for delivering the trap. In the case of seccomp(2), the tracee will be shown as delivering the event. BUS_MCEERR_* and si_addr_lsb are Linux-specific extensions.

The SEGV_BNDERR suberror of SIGSEGV populates si_lower and si_upper.

The SEGV_PKUERR suberror of SIGSEGV populates si_pkey.

•

SIGIO/SIGPOLL (the two names are synonyms on Linux) fills in si_band and si_fd. The si_band event is a bit mask containing the same values as are filled in the revents field by poll(2). The si_fd field indicates the file descriptor for which the I/O event occurred; for further details, see the description of F_SETSIG in fcntl(2).

•

SIGSYS, generated (since Linux 3.5) when a seccomp filter returns SECCOMP_RET_TRAP, fills in si_call_addr, si_syscall, si_arch, si_errno, and other fields as described in seccomp(2).

### The si_code field
The si_code field inside the siginfo_t argument that is passed to a SA_SIGINFO signal handler is a value (not a bit mask) indicating why this signal was sent. For a ptrace(2) event, si_code will contain SIGTRAP and have the ptrace event in the high byte:

```
(SIGTRAP | PTRACE_EVENT_foo << 8).
```

For a non-ptrace(2) event, the values that can appear in si_code are described in the remainder of this section. Since glibc 2.20, the definitions of most of these symbols are obtained from <signal.h> by defining feature test macros (before including any header file) as follows:

•

_XOPEN_SOURCE with the value 500 or greater;

•

_XOPEN_SOURCE and _XOPEN_SOURCE_EXTENDED; or

•

_POSIX_C_SOURCE with the value 200809L or greater.

For the TRAP_* constants, the symbol definitions are provided only in the first two cases. Before glibc 2.20, no feature test macros were required to obtain these symbols.

For a regular signal, the following list shows the values which can be placed in si_code for any signal, along with the reason that the signal was generated.

SI_USER

kill(2).

SI_KERNEL

Sent by the kernel.

SI_QUEUE

sigqueue(3).

SI_TIMER

POSIX timer expired.

SI_MESGQ (since Linux 2.6.6)

POSIX message queue state changed; see mq_notify(3).

SI_ASYNCIO

AIO completed.

SI_SIGIO

Queued SIGIO (only up to Linux 2.2; from Linux 2.4 onward SIGIO/SIGPOLL fills in si_code as described below).

SI_TKILL (since Linux 2.4.19)

tkill(2) or tgkill(2).

The following values can be placed in si_code for a SIGILL signal:

ILL_ILLOPC

Illegal opcode.

ILL_ILLOPN

Illegal operand.

ILL_ILLADR

Illegal addressing mode.

ILL_ILLTRP

Illegal trap.

ILL_PRVOPC

Privileged opcode.

ILL_PRVREG

Privileged register.

ILL_COPROC

Coprocessor error.

ILL_BADSTK

Internal stack error.

The following values can be placed in si_code for a SIGFPE signal:

FPE_INTDIV

Integer divide by zero.

FPE_INTOVF

Integer overflow.

FPE_FLTDIV

Floating-point divide by zero.

FPE_FLTOVF

Floating-point overflow.

FPE_FLTUND

Floating-point underflow.

FPE_FLTRES

Floating-point inexact result.

FPE_FLTINV

Floating-point invalid operation.

FPE_FLTSUB

Subscript out of range.

The following values can be placed in si_code for a SIGSEGV signal:

SEGV_MAPERR

Address not mapped to object.

SEGV_ACCERR

Invalid permissions for mapped object.

SEGV_BNDERR (since Linux 3.19)

Failed address bound checks.

SEGV_PKUERR (since Linux 4.6)

Access was denied by memory protection keys. See pkeys(7). The protection key which applied to this access is available via si_pkey.

The following values can be placed in si_code for a SIGBUS signal:

BUS_ADRALN

Invalid address alignment.

BUS_ADRERR

Nonexistent physical address.

BUS_OBJERR

Object-specific hardware error.

BUS_MCEERR_AR (since Linux 2.6.32)

Hardware memory error consumed on a machine check; action required.

BUS_MCEERR_AO (since Linux 2.6.32)

Hardware memory error detected in process but not consumed; action optional.

The following values can be placed in si_code for a SIGTRAP signal:

TRAP_BRKPT

Process breakpoint.

TRAP_TRACE

Process trace trap.

TRAP_BRANCH (since Linux 2.4, IA64 only)

Process taken branch trap.

TRAP_HWBKPT (since Linux 2.4, IA64 only)

Hardware breakpoint/watchpoint.

The following values can be placed in si_code for a SIGCHLD signal:

CLD_EXITED

Child has exited.

CLD_KILLED

Child was killed.

CLD_DUMPED

Child terminated abnormally.

CLD_TRAPPED

Traced child has trapped.

CLD_STOPPED

Child has stopped.

CLD_CONTINUED (since Linux 2.6.9)

Stopped child has continued.

The following values can be placed in si_code for a SIGIO/SIGPOLL signal:

POLL_IN

Data input available.

POLL_OUT

Output buffers available.

POLL_MSG

Input message available.

POLL_ERR

I/O error.

POLL_PRI

High priority input available.

POLL_HUP

Device disconnected.

The following value can be placed in si_code for a SIGSYS signal:

SYS_SECCOMP (since Linux 3.5)

Triggered by a seccomp(2) filter rule.

### Dynamically probing for flag bit support
The sigaction() call on Linux accepts unknown bits set in act->sa_flags without error. The behavior of the kernel starting with Linux 5.11 is that a second sigaction() will clear unknown bits from oldact->sa_flags. However, historically, a second sigaction() call would typically leave those bits set in oldact->sa_flags.

This means that support for new flags cannot be detected simply by testing for a flag in sa_flags, and a program must test that SA_UNSUPPORTED has been cleared before relying on the contents of sa_flags.

Since the behavior of the signal handler cannot be guaranteed unless the check passes, it is wise to either block the affected signal while registering the handler and performing the check in this case, or where this is not possible, for example if the signal is synchronous, to issue the second sigaction() in the signal handler itself.

In kernels that do not support a specific flag, the kernel's behavior is as if the flag was not set, even if the flag was set in act->sa_flags.

The flags SA_NOCLDSTOP, SA_NOCLDWAIT, SA_SIGINFO, SA_ONSTACK, SA_RESTART, SA_NODEFER, SA_RESETHAND, and, if defined by the architecture, SA_RESTORER may not be reliably probed for using this mechanism, because they were introduced before Linux 5.11. However, in general, programs may assume that these flags are supported, since they have all been supported since Linux 2.6, which was released in the year 2003.

See EXAMPLES below for a demonstration of the use of SA_UNSUPPORTED.

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

## ERRORS
EFAULT

act or oldact points to memory which is not a valid part of the process address space.

EINVAL

An invalid signal was specified. This will also be generated if an attempt is made to change the action for SIGKILL or SIGSTOP, which cannot be caught or ignored.

## VERSIONS

### C library/kernel differences
The glibc wrapper function for sigaction() gives an error (EINVAL) on attempts to change the disposition of the two real-time signals used internally by the NPTL threading implementation. See nptl(7) for details.

On architectures where the signal trampoline resides in the C library, the glibc wrapper function for sigaction() places the address of the trampoline code in the act.sa_restorer field and sets the SA_RESTORER flag in the act.sa_flags field. See sigreturn(2).

The original Linux system call was named sigaction(). However, with the addition of real-time signals in Linux 2.2, the fixed-size, 32-bit sigset_t type supported by that system call was no longer fit for purpose. Consequently, a new system call, rt_sigaction(), was added to support an enlarged sigset_t type. The new system call takes a fourth argument, size_t sigsetsize, which specifies the size in bytes of the signal sets in act.sa_mask and oldact.sa_mask. This argument is currently required to have the value sizeof(sigset_t) (or the error EINVAL results). The glibc sigaction() wrapper function hides these details from us, transparently calling rt_sigaction() when the kernel provides it.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4.

POSIX.1-1990 disallowed setting the action for SIGCHLD to SIG_IGN. POSIX.1-2001 and later allow this possibility, so that ignoring SIGCHLD can be used to prevent the creation of zombies (see wait(2)). Nevertheless, the historical BSD and System V behaviors for ignoring SIGCHLD differ, so that the only completely portable method of ensuring that terminated children do not become zombies is to catch the SIGCHLD signal and perform a wait(2) or similar.

POSIX.1-1990 specified only SA_NOCLDSTOP. POSIX.1-2001 added SA_NOCLDSTOP, SA_NOCLDWAIT, SA_NODEFER, SA_ONSTACK, SA_RESETHAND, SA_RESTART, and SA_SIGINFO. Use of these latter values in sa_flags may be less portable in applications intended for older UNIX implementations.

The SA_RESETHAND flag is compatible with the SVr4 flag of the same name.

The SA_NODEFER flag is compatible with the SVr4 flag of the same name under kernels 1.3.9 and later. On older kernels the Linux implementation allowed the receipt of any signal, not just the one we are installing (effectively overriding any sa_mask settings).

## NOTES
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.

According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(2) or raise(3). Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal. (Also dividing the most negative integer by -1 may generate SIGFPE.) Ignoring this signal might lead to an endless loop.

sigaction() can be called with a NULL second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with NULL second and third arguments.

It is not possible to block SIGKILL or SIGSTOP (by specifying them in sa_mask). Attempts to do so are silently ignored.

See sigsetops(3) for details on manipulating signal sets.

See signal-safety(7) for a list of the async-signal-safe functions that can be safely called inside from inside a signal handler.

### Undocumented
Before the introduction of SA_SIGINFO, it was also possible to get some additional information about the signal. This was done by providing an sa_handler signal handler with a second argument of type struct sigcontext, which is the same structure as the one that is passed in the uc_mcontext field of the ucontext structure that is passed (via a pointer) in the third argument of the sa_sigaction handler. See the relevant Linux kernel sources for details. This use is obsolete now.

## BUGS
When delivering a signal with a SA_SIGINFO handler, the kernel does not always provide meaningful values for all of the fields of the siginfo_t that are relevant for that signal.

Up to and including Linux 2.6.13, specifying SA_NODEFER in sa_flags prevents not only the delivered signal from being masked during execution of the handler, but also the signals specified in sa_mask. This bug was fixed in Linux 2.6.14.

## EXAMPLES
See mprotect(2).

### Probing for flag support
The following example program exits with status EXIT_SUCCESS if SA_EXPOSE_TAGBITS is determined to be supported, and EXIT_FAILURE otherwise.

```
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void
handler(int signo, siginfo_t *info, void *context)
{

    struct sigaction oldact;

    if (sigaction(SIGSEGV, NULL, &oldact) == -1

        || (oldact.sa_flags & SA_UNSUPPORTED)

        || !(oldact.sa_flags & SA_EXPOSE_TAGBITS))

    {

        _exit(EXIT_FAILURE);

    }

    _exit(EXIT_SUCCESS);
}
int
main(void)
{

    struct sigaction act = { 0 };

    act.sa_flags = SA_SIGINFO | SA_UNSUPPORTED | SA_EXPOSE_TAGBITS;

    act.sa_sigaction = &handler;

    if (sigaction(SIGSEGV, &act, NULL) == -1) {

        perror("sigaction");

        exit(EXIT_FAILURE);

    }

    raise(SIGSEGV);
}
```

## SEE ALSO
kill(1), kill(2), pause(2), pidfd_send_signal(2), restart_syscall(2), seccomp(2), sigaltstack(2), signal(2), signalfd(2), sigpending(2), sigprocmask(2), sigreturn(2), sigsuspend(2), wait(2), killpg(3), raise(3), siginterrupt(3), sigqueue(3), sigsetops(3), sigvec(3), core(5), signal(7)


sigaltstack

title: sigaltstack(2)

summary: set and/or get signal stack context

text:
# sigaltstack(2)

## NAME
sigaltstack - set and/or get signal stack context

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

## SYNOPSIS

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

```
int sigaltstack(const stack_t *_Nullable restrict ss,
                stack_t *_Nullable restrict old_ss);
```

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

sigaltstack():

```
    _XOPEN_SOURCE >= 500

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

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

## DESCRIPTION
sigaltstack() allows a thread to define a new alternate signal stack and/or retrieve the state of an existing alternate signal stack. An alternate signal stack is used during the execution of a signal handler if the establishment of that handler (see sigaction(2)) requested it.

The normal sequence of events for using an alternate signal stack is the following:

1.

Allocate an area of memory to be used for the alternate signal stack.

2.

Use sigaltstack() to inform the system of the existence and location of the alternate signal stack.

3.

When establishing a signal handler using sigaction(2), inform the system that the signal handler should be executed on the alternate signal stack by specifying the SA_ONSTACK flag.

The ss argument is used to specify a new alternate signal stack, while the old_ss argument is used to retrieve information about the currently established signal stack. If we are interested in performing just one of these tasks, then the other argument can be specified as NULL.

The stack_t type used to type the arguments of this function is defined as follows:

```
typedef struct {

    void  *ss_sp;     /* Base address of stack */

    int    ss_flags;  /* Flags */

    size_t ss_size;   /* Number of bytes in stack */
} stack_t;
```

To establish a new alternate signal stack, the fields of this structure are set as follows:

ss.ss_flags

This field contains either 0, or the following flag:

SS_AUTODISARM (since Linux 4.7)

Clear the alternate signal stack settings on entry to the signal handler. When the signal handler returns, the previous alternate signal stack settings are restored.

This flag was added in order to make it safe to switch away from the signal handler with swapcontext(3). Without this flag, a subsequently handled signal will corrupt the state of the switched-away signal handler. On kernels where this flag is not supported, sigaltstack() fails with the error EINVAL when this flag is supplied.

ss.ss_sp

This field specifies the starting address of the stack. When a signal handler is invoked on the alternate stack, the kernel automatically aligns the address given in ss.ss_sp to a suitable address boundary for the underlying hardware architecture.

ss.ss_size

This field specifies the size of the stack. The constant SIGSTKSZ is defined to be large enough to cover the usual size requirements for an alternate signal stack, and the constant MINSIGSTKSZ defines the minimum size required to execute a signal handler.

To disable an existing stack, specify ss.ss_flags as SS_DISABLE. In this case, the kernel ignores any other flags in ss.ss_flags and the remaining fields in ss.

If old_ss is not NULL, then it is used to return information about the alternate signal stack which was in effect prior to the call to sigaltstack(). The old_ss.ss_sp and old_ss.ss_size fields return the starting address and size of that stack. The old_ss.ss_flags may return either of the following values:

SS_ONSTACK

The thread is currently executing on the alternate signal stack. (Note that it is not possible to change the alternate signal stack if the thread is currently executing on it.)

SS_DISABLE

The alternate signal stack is currently disabled.

Alternatively, this value is returned if the thread is currently executing on an alternate signal stack that was established using the SS_AUTODISARM flag. In this case, it is safe to switch away from the signal handler with swapcontext(3). It is also possible to set up a different alternative signal stack using a further call to sigaltstack().

SS_AUTODISARM

The alternate signal stack has been marked to be autodisarmed as described above.

By specifying ss as NULL, and old_ss as a non-NULL value, one can obtain the current settings for the alternate signal stack without changing them.

## RETURN VALUE
sigaltstack() returns 0 on success, or -1 on failure with errno set to indicate the error.

## ERRORS
EFAULT

Either ss or old_ss is not NULL and points to an area outside of the process's address space.

EINVAL

ss is not NULL and the ss_flags field contains an invalid flag.

ENOMEM

The specified size of the new alternate signal stack ss.ss_size was less than MINSIGSTKSZ.

EPERM

An attempt was made to change the alternate signal stack while it was active (i.e., the thread was already executing on the current alternate signal stack).

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

Interface

Attribute

Value

sigaltstack ()

Thread safety

MT-Safe

## STANDARDS
POSIX.1-2008.

SS_AUTODISARM is a Linux extension.

## HISTORY
POSIX.1-2001, SUSv2, SVr4.

## NOTES
The most common usage of an alternate signal stack is to handle the SIGSEGV signal that is generated if the space available for the standard stack is exhausted: in this case, a signal handler for SIGSEGV cannot be invoked on the standard stack; if we wish to handle it, we must use an alternate signal stack.

Establishing an alternate signal stack is useful if a thread expects that it may exhaust its standard stack. This may occur, for example, because the stack grows so large that it encounters the upwardly growing heap, or it reaches a limit established by a call to setrlimit(RLIMIT_STACK, &rlim). If the standard stack is exhausted, the kernel sends the thread a SIGSEGV signal. In these circumstances the only way to catch this signal is on an alternate signal stack.

On most hardware architectures supported by Linux, stacks grow downward. sigaltstack() automatically takes account of the direction of stack growth.

Functions called from a signal handler executing on an alternate signal stack will also use the alternate signal stack. (This also applies to any handlers invoked for other signals while the thread is executing on the alternate signal stack.) Unlike the standard stack, the system does not automatically extend the alternate signal stack. Exceeding the allocated size of the alternate signal stack will lead to unpredictable results.

A successful call to execve(2) removes any existing alternate signal stack. A child process created via fork(2) inherits a copy of its parent's alternate signal stack settings. The same is also true for a child process created using clone(2), unless the clone flags include CLONE_VM and do not include CLONE_VFORK, in which case any alternate signal stack that was established in the parent is disabled in the child process.

sigaltstack() supersedes the older sigstack() call. For backward compatibility, glibc also provides sigstack(). All new applications should be written using sigaltstack().

### History
4.2BSD had a sigstack() system call. It used a slightly different struct, and had the major disadvantage that the caller had to know the direction of stack growth.

## BUGS
In Linux 2.2 and earlier, the only flag that could be specified in ss.sa_flags was SS_DISABLE. In the lead up to the release of the Linux 2.4 kernel, a change was made to allow sigaltstack() to allow ss.ss_flags==SS_ONSTACK with the same meaning as ss.ss_flags==0 (i.e., the inclusion of SS_ONSTACK in ss.ss_flags is a no-op). On other implementations, and according to POSIX.1, SS_ONSTACK appears only as a reported flag in old_ss.ss_flags. On Linux, there is no need ever to specify SS_ONSTACK in ss.ss_flags, and indeed doing so should be avoided on portability grounds: various other systems give an error if SS_ONSTACK is specified in ss.ss_flags.

## EXAMPLES
The following code segment demonstrates the use of sigaltstack() (and sigaction(2)) to install an alternate signal stack that is employed by a handler for the SIGSEGV signal:

```
stack_t ss;
ss.ss_sp = malloc(SIGSTKSZ);
if (ss.ss_sp == NULL) {

    perror("malloc");

    exit(EXIT_FAILURE);
}
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
if (sigaltstack(&ss, NULL) == -1) {

    perror("sigaltstack");

    exit(EXIT_FAILURE);
}
sa.sa_flags = SA_ONSTACK;
sa.sa_handler = handler();      /* Address of a signal handler */
sigemptyset(&sa.sa_mask);
if (sigaction(SIGSEGV, &sa, NULL) == -1) {

    perror("sigaction");

    exit(EXIT_FAILURE);
}
```

## SEE ALSO
execve(2), setrlimit(2), sigaction(2), siglongjmp(3), sigsetjmp(3), signal(7)


signal

title: signal(2)

summary: ANSI C signal handling

text:
# signal(2)

## NAME
signal - ANSI C signal handling

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

## SYNOPSIS

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

```
typedef void (*sighandler_t)(int);
```

```
sighandler_t signal(int signum, sighandler_t handler);
```

## DESCRIPTION
WARNING: the behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead. See Portability below.

signal() sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler").

If the signal signum is delivered to the process, then one of the following happens:

*

If the disposition is set to SIG_IGN, then the signal is ignored.

*

If the disposition is set to SIG_DFL, then the default action associated with the signal (see signal(7)) occurs.

*

If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or the signal is blocked (see Portability below), and then handler is called with argument signum. If invocation of the handler caused the signal to be blocked, then the signal is unblocked upon return from the handler.

The signals SIGKILL and SIGSTOP cannot be caught or ignored.

## RETURN VALUE
signal() returns the previous value of the signal handler. On failure, it returns SIG_ERR, and errno is set to indicate the error.

## ERRORS
EINVAL

signum is invalid.

## VERSIONS
The use of sighandler_t is a GNU extension, exposed if _GNU_SOURCE is defined; glibc also defines (the BSD-derived) sig_t if _BSD_SOURCE (glibc 2.19 and earlier) or _DEFAULT_SOURCE (glibc 2.19 and later) is defined. Without use of such a type, the declaration of signal() is the somewhat harder to read:

```
void ( *signal(int signum, void (*handler)(int)) ) (int);
```

### Portability
The only portable use of signal() is to set a signal's disposition to SIG_DFL or SIG_IGN. The semantics when using signal() to establish a signal handler vary across systems (and POSIX.1 explicitly permits this variation); do not use it for this purpose.

POSIX.1 solved the portability mess by specifying sigaction(2), which provides explicit control of the semantics when a signal handler is invoked; use that interface instead of signal().

## STANDARDS
C11, POSIX.1-2008.

## HISTORY
C89, POSIX.1-2001.

In the original UNIX systems, when a handler that was established using signal() was invoked by the delivery of a signal, the disposition of the signal would be reset to SIG_DFL, and the system did not block delivery of further instances of the signal. This is equivalent to calling sigaction(2) with the following flags:

```
sa.sa_flags = SA_RESETHAND | SA_NODEFER;
```

System V also provides these semantics for signal(). This was bad because the signal might be delivered again before the handler had a chance to reestablish itself. Furthermore, rapid deliveries of the same signal could result in recursive invocations of the handler.

BSD improved on this situation, but unfortunately also changed the semantics of the existing signal() interface while doing so. On BSD, when a signal handler is invoked, the signal disposition is not reset, and further instances of the signal are blocked from being delivered while the handler is executing. Furthermore, certain blocking system calls are automatically restarted if interrupted by a signal handler (see signal(7)). The BSD semantics are equivalent to calling sigaction(2) with the following flags:

```
sa.sa_flags = SA_RESTART;
```

The situation on Linux is as follows:

•

The kernel's signal() system call provides System V semantics.

•

By default, in glibc 2 and later, the signal() wrapper function does not invoke the kernel system call. Instead, it calls sigaction(2) using flags that supply BSD semantics. This default behavior is provided as long as a suitable feature test macro is defined: _BSD_SOURCE on glibc 2.19 and earlier or _DEFAULT_SOURCE in glibc 2.19 and later. (By default, these macros are defined; see feature_test_macros(7) for details.) If such a feature test macro is not defined, then signal() provides System V semantics.

## NOTES
The effects of signal() in a multithreaded process are unspecified.

According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(2) or raise(3). Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal. (Also dividing the most negative integer by -1 may generate SIGFPE.) Ignoring this signal might lead to an endless loop.

See sigaction(2) for details on what happens when the disposition SIGCHLD is set to SIG_IGN.

See signal-safety(7) for a list of the async-signal-safe functions that can be safely called from inside a signal handler.

## SEE ALSO
kill(1), alarm(2), kill(2), pause(2), sigaction(2), signalfd(2), sigpending(2), sigprocmask(2), sigsuspend(2), bsd_signal(3), killpg(3), raise(3), siginterrupt(3), sigqueue(3), sigsetops(3), sigvec(3), sysv_signal(3), signal(7)


signalfd

title: signalfd(2)

text:
# signalfd(2)

## NAME
signalfd - create a file descriptor for accepting signals

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

## SYNOPSIS

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

```
int signalfd(int fd, const sigset_t *mask, int flags);
```

## DESCRIPTION
signalfd() creates a file descriptor that can be used to accept signals targeted at the caller. This provides an alternative to the use of a signal handler or sigwaitinfo(2), and has the advantage that the file descriptor may be monitored by select(2), poll(2), and epoll(7).

The mask argument specifies the set of signals that the caller wishes to accept via the file descriptor. This argument is a signal set whose contents can be initialized using the macros described in sigsetops(3). Normally, the set of signals to be received via the file descriptor should be blocked using sigprocmask(2), to prevent the signals being handled according to their default dispositions. It is not possible to receive SIGKILL or SIGSTOP signals via a signalfd file descriptor; these signals are silently ignored if specified in mask.

If the fd argument is -1, then the call creates a new file descriptor and associates the signal set specified in mask with that file descriptor. If fd is not -1, then it must specify a valid existing signalfd file descriptor, and mask is used to replace the signal set associated with that file descriptor.

Starting with Linux 2.6.27, the following values may be bitwise ORed in flags to change the behavior of signalfd():

SFD_NONBLOCK

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

SFD_CLOEXEC

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

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

signalfd() returns a file descriptor that supports the following operations:

read(2)

If one or more of the signals specified in mask is pending for the process, then the buffer supplied to read(2) is used to return one or more signalfd_siginfo structures (see below) that describe the signals. The read(2) returns information for as many signals as are pending and will fit in the supplied buffer. The buffer must be at least sizeof(struct signalfd_siginfo) bytes. The return value of the read(2) is the total number of bytes read.

As a consequence of the read(2), the signals are consumed, so that they are no longer pending for the process (i.e., will not be caught by signal handlers, and cannot be accepted using sigwaitinfo(2)).

If none of the signals in mask is pending for the process, then the read(2) either blocks until one of the signals in mask is generated for the process, or fails with the error EAGAIN if the file descriptor has been made nonblocking.

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

The file descriptor is readable (the select(2) readfds argument; the poll(2) POLLIN flag) if one or more of the signals in mask is pending for the process.

The signalfd file descriptor also supports the other file-descriptor multiplexing APIs: pselect(2), ppoll(2), and epoll(7).

close(2)

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

### The signalfd_siginfo structure
The format of the signalfd_siginfo structure(s) returned by read(2)s from a signalfd file descriptor is as follows:

```
struct signalfd_siginfo {

    uint32_t ssi_signo;    /* Signal number */

    int32_t  ssi_errno;    /* Error number (unused) */

    int32_t  ssi_code;     /* Signal code */

    uint32_t ssi_pid;      /* PID of sender */

    uint32_t ssi_uid;      /* Real UID of sender */

    int32_t  ssi_fd;       /* File descriptor (SIGIO) */

    uint32_t ssi_tid;      /* Kernel timer ID (POSIX timers)

    uint32_t ssi_band;     /* Band event (SIGIO) */

    uint32_t ssi_overrun;  /* POSIX timer overrun count */

    uint32_t ssi_trapno;   /* Trap number that caused signal */

    int32_t  ssi_status;   /* Exit status or signal (SIGCHLD) */

    int32_t  ssi_int;      /* Integer sent by sigqueue(3) */

    uint64_t ssi_ptr;      /* Pointer sent by sigqueue(3) */

    uint64_t ssi_utime;    /* User CPU time consumed (SIGCHLD) */

    uint64_t ssi_stime;    /* System CPU time consumed

                              (SIGCHLD) */

    uint64_t ssi_addr;     /* Address that generated signal

                              (for hardware-generated signals) */

    uint16_t ssi_addr_lsb; /* Least significant bit of address

                              (SIGBUS; since Linux 2.6.37) */

    uint8_t  pad[X];       /* Pad size to 128 bytes (allow for

                              additional fields in the future) */
};
```

Each of the fields in this structure is analogous to the similarly named field in the siginfo_t structure. The siginfo_t structure is described in sigaction(2). Not all fields in the returned signalfd_siginfo structure will be valid for a specific signal; the set of valid fields can be determined from the value returned in the ssi_code field. This field is the analog of the siginfo_t si_code field; see sigaction(2) for details.

### fork(2) semantics
After a fork(2), the child inherits a copy of the signalfd file descriptor. A read(2) from the file descriptor in the child will return information about signals queued to the child.

### Semantics of file descriptor passing
As with other file descriptors, signalfd file descriptors can be passed to another process via a UNIX domain socket (see unix(7)). In the receiving process, a read(2) from the received file descriptor will return information about signals queued to that process.

### execve(2) semantics
Just like any other file descriptor, a signalfd file descriptor remains open across an execve(2), unless it has been marked for close-on-exec (see fcntl(2)). Any signals that were available for reading before the execve(2) remain available to the newly loaded program. (This is analogous to traditional signal semantics, where a blocked signal that is pending remains pending across an execve(2).)

### Thread semantics
The semantics of signalfd file descriptors in a multithreaded program mirror the standard semantics for signals. In other words, when a thread reads from a signalfd file descriptor, it will read the signals that are directed to the thread itself and the signals that are directed to the process (i.e., the entire thread group). (A thread will not be able to read signals that are directed to other threads in the process.)

### epoll(7) semantics
If a process adds (via epoll_ctl(2)) a signalfd file descriptor to an epoll(7) instance, then epoll_wait(2) returns events only for signals sent to that process. In particular, if the process then uses fork(2) to create a child process, then the child will be able to read(2) signals that are sent to it using the signalfd file descriptor, but epoll_wait(2) will not indicate that the signalfd file descriptor is ready. In this scenario, a possible workaround is that after the fork(2), the child process can close the signalfd file descriptor that it inherited from the parent process and then create another signalfd file descriptor and add it to the epoll instance. Alternatively, the parent and the child could delay creating their (separate) signalfd file descriptors and adding them to the epoll instance until after the call to fork(2).

## RETURN VALUE
On success, signalfd() returns a signalfd file descriptor; this is either a new file descriptor (if fd was -1), or fd if fd was a valid signalfd file descriptor. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EBADF

The fd file descriptor is not a valid file descriptor.

EINVAL

fd is not a valid signalfd file descriptor.

EINVAL

flags is invalid; or, in Linux 2.6.26 or earlier, flags is nonzero.

EMFILE

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

ENFILE

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

ENODEV

Could not mount (internal) anonymous inode device.

ENOMEM

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

## VERSIONS

### C library/kernel differences
The underlying Linux system call requires an additional argument, size_t sizemask, which specifies the size of the mask argument. The glibc signalfd() wrapper function does not include this argument, since it provides the required value for the underlying system call.

There are two underlying Linux system calls: signalfd() and the more recent signalfd4(). The former system call does not implement a flags argument. The latter system call implements the flags values described above. Starting with glibc 2.9, the signalfd() wrapper function will use signalfd4() where it is available.

## STANDARDS
Linux.

## HISTORY
signalfd()

Linux 2.6.22, glibc 2.8.

signalfd4()

Linux 2.6.27.

## NOTES
A process can create multiple signalfd file descriptors. This makes it possible to accept different signals on different file descriptors. (This may be useful if monitoring the file descriptors using select(2), poll(2), or epoll(7): the arrival of different signals will make different file descriptors ready.) If a signal appears in the mask of more than one of the file descriptors, then occurrences of that signal can be read (once) from any one of the file descriptors.

Attempts to include SIGKILL and SIGSTOP in mask are silently ignored.

The signal mask employed by a signalfd file descriptor can be viewed via the entry for the corresponding file descriptor in the process's /proc/pid/fdinfo directory. See proc(5) for further details.

### Limitations
The signalfd mechanism can't be used to receive signals that are synchronously generated, such as the SIGSEGV signal that results from accessing an invalid memory address or the SIGFPE signal that results from an arithmetic error. Such signals can be caught only via signal handler.

As described above, in normal usage one blocks the signals that will be accepted via signalfd(). If spawning a child process to execute a helper program (that does not need the signalfd file descriptor), then, after the call to fork(2), you will normally want to unblock those signals before calling execve(2), so that the helper program can see any signals that it expects to see. Be aware, however, that this won't be possible in the case of a helper program spawned behind the scenes by any library function that the program may call. In such cases, one must fall back to using a traditional signal handler that writes to a file descriptor monitored by select(2), poll(2), or epoll(7).

## BUGS
Before Linux 2.6.25, the ssi_ptr and ssi_int fields are not filled in with the data accompanying a signal sent by sigqueue(3).

## EXAMPLES
The program below accepts the signals SIGINT and SIGQUIT via a signalfd file descriptor. The program terminates after accepting a SIGQUIT signal. The following shell session demonstrates the use of the program:

```
$ ./signalfd_demo
^C                   # Control-C generates SIGINT
Got SIGINT
^C
Got SIGINT
^\                    # Control-\ generates SIGQUIT
Got SIGQUIT
$
```

### Program source

```
#include <err.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/signalfd.h>
#include <unistd.h>
int
main(void)
{

    int                      sfd;

    ssize_t                  s;

    sigset_t                 mask;

    struct signalfd_siginfo  fdsi;

    sigemptyset(&mask);

    sigaddset(&mask, SIGINT);

    sigaddset(&mask, SIGQUIT);

    /* Block signals so that they aren't handled

       according to their default dispositions. */

    if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)

        err(EXIT_FAILURE, "sigprocmask");

    sfd = signalfd(-1, &mask, 0);

    if (sfd == -1)

        err(EXIT_FAILURE, "signalfd");

    for (;;) {

        s = read(sfd, &fdsi, sizeof(fdsi));

        if (s != sizeof(fdsi))

            err(EXIT_FAILURE, "read");

        if (fdsi.ssi_signo == SIGINT) {

            printf("Got SIGINT\n");

        } else if (fdsi.ssi_signo == SIGQUIT) {

            printf("Got SIGQUIT\n");

            exit(EXIT_SUCCESS);

        } else {

            printf("Read unexpected signal\n");

        }

    }
}
```

## SEE ALSO
eventfd(2), poll(2), read(2), select(2), sigaction(2), sigprocmask(2), sigwaitinfo(2), timerfd_create(2), sigsetops(3), sigwait(3), epoll(7), signal(7)