semctl

title: semctl(2)

summary: System V semaphore control operations

text:
# semctl(2)

## NAME
semctl - System V semaphore control operations

## SYNOPSIS

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

```
int semctl(int semid, int semnum, int cmd, ...);
```

## DESCRIPTION
semctl() performs the control operation specified by cmd on the System V semaphore set identified by semid, or on the semnum-th semaphore of that set. (The semaphores in a set are numbered starting at 0.)

This function has three or four arguments, depending on cmd. When there are four, the fourth has the type union semun. The calling program must define this union as follows:

```
union semun {

    int              val;    /* Value for SETVAL */

    struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */

    unsigned short  *array;  /* Array for GETALL, SETALL */

    struct seminfo  *__buf;  /* Buffer for IPC_INFO

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

The semid_ds data structure is defined in <sys/sem.h> as follows:

```
struct semid_ds {

    struct ipc_perm sem_perm;  /* Ownership and permissions */

    time_t          sem_otime; /* Last semop time */

    time_t          sem_ctime; /* Creation time/time of last

                                  modification via semctl() */

    unsigned long   sem_nsems; /* No. of semaphores in set */
};
```

The fields of the semid_ds structure are as follows:

sem_perm

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

sem_otime

Time of last semop(2) system call.

sem_ctime

Time of creation of semaphore set or time of last semctl() IPCSET, SETVAL, or SETALL operation.

sem_nsems

Number of semaphores in the set. Each semaphore of the set is referenced by a nonnegative integer ranging from 0 to sem_nsems-1.

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 semget(2) */

    uid_t          uid;   /* Effective UID of owner */

    gid_t          gid;   /* Effective GID of owner */

    uid_t          cuid;  /* Effective UID of creator */

    gid_t          cgid;  /* Effective GID of creator */

    unsigned short mode;  /* Permissions */

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

The least significant 9 bits of the mode field of the ipc_perm structure define the access permissions for the 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

In effect, "write" means "alter" for a semaphore set. Bits 0100, 0010, and 0001 (the execute bits) are unused by the system.

Valid values for cmd are:

IPC_STAT

Copy information from the kernel data structure associated with semid into the semid_ds structure pointed to by arg.buf. The argument semnum is ignored. The calling process must have read permission on the semaphore set.

IPC_SET

Write the values of some members of the semid_ds structure pointed to by arg.buf to the kernel data structure associated with this semaphore set, updating also its sem_ctime member.

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

The effective UID of the calling process must match the owner (sem_perm.uid) or creator (sem_perm.cuid) of the semaphore set, or the caller must be privileged. The argument semnum is ignored.

IPC_RMID

Immediately remove the semaphore set, awakening all processes blocked in semop(2) calls on the set (with an error return and errno set to EIDRM). The effective user ID of the calling process must match the creator or owner of the semaphore set, or the caller must be privileged. The argument semnum is ignored.

IPC_INFO (Linux-specific)

Return information about system-wide semaphore limits and parameters in the structure pointed to by arg.__buf. This structure is of type seminfo, defined in <sys/sem.h> if the _GNU_SOURCE feature test macro is defined:

```
struct  seminfo {

    int semmap;  /* Number of entries in semaphore

                    map; unused within kernel */

    int semmni;  /* Maximum number of semaphore sets */

    int semmns;  /* Maximum number of semaphores in all

                    semaphore sets */

    int semmnu;  /* System-wide maximum number of undo

                    structures; unused within kernel */

    int semmsl;  /* Maximum number of semaphores in a

                    set */

    int semopm;  /* Maximum number of operations for

                    semop(2) */

    int semume;  /* Maximum number of undo entries per

                    process; unused within kernel */

    int semusz;  /* Size of struct sem_undo */

    int semvmx;  /* Maximum semaphore value */

    int semaem;  /* Max. value that can be recorded for

                    semaphore adjustment (SEM_UNDO) */
};

```

The semmsl, semmns, semopm, and semmni settings can be changed via /proc/sys/kernel/sem; see proc(5) for details.

SEM_INFO (Linux-specific)

Return a seminfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by semaphores: the semusz field returns the number of semaphore sets that currently exist on the system; and the semaem field returns the total number of semaphores in all semaphore sets on the system.

SEM_STAT (Linux-specific)

Return a semid_ds structure as for IPC_STAT. However, the semid argument is not a semaphore identifier, but instead an index into the kernel's internal array that maintains information about all semaphore sets on the system.

SEM_STAT_ANY (Linux-specific, since Linux 4.17)

Return a semid_ds structure as for SEM_STAT. However, sem_perm.mode is not checked for read access for semid meaning that any user can employ this operation (just as any user may read /proc/sysvipc/sem to obtain the same information).

GETALL

Return semval (i.e., the current value) for all semaphores of the set into arg.array. The argument semnum is ignored. The calling process must have read permission on the semaphore set.

GETNCNT

Return the semncnt value for the semnum-th semaphore of the set (i.e., the number of processes waiting for the semaphore's value to increase). The calling process must have read permission on the semaphore set.

GETPID

Return the sempid value for the semnum-th semaphore of the set. This is the PID of the process that last performed an operation on that semaphore (but see NOTES). The calling process must have read permission on the semaphore set.

GETVAL

Return semval (i.e., the semaphore value) for the semnum-th semaphore of the set. The calling process must have read permission on the semaphore set.

GETZCNT

Return the semzcnt value for the semnum-th semaphore of the set (i.e., the number of processes waiting for the semaphore value to become 0). The calling process must have read permission on the semaphore set.

SETALL

Set the semval values for all semaphores of the set using arg.array, updating also the sem_ctime member of the semid_ds structure associated with the set. Undo entries (see semop(2)) are cleared for altered semaphores in all processes. If the changes to semaphore values would permit blocked semop(2) calls in other processes to proceed, then those processes are woken up. The argument semnum is ignored. The calling process must have alter (write) permission on the semaphore set.

SETVAL

Set the semaphore value (semval) to arg.val for the semnum-th semaphore of the set, updating also the sem_ctime member of the semid_ds structure associated with the set. Undo entries are cleared for altered semaphores in all processes. If the changes to semaphore values would permit blocked semop(2) calls in other processes to proceed, then those processes are woken up. The calling process must have alter permission on the semaphore set.

## RETURN VALUE
On success, semctl() returns a nonnegative value depending on cmd as follows:

GETNCNT

the value of semncnt.

GETPID

the value of sempid.

GETVAL

the value of semval.

GETZCNT

the value of semzcnt.

IPC_INFO

the index of the highest used entry in the kernel's internal array recording information about all semaphore sets. (This information can be used with repeated SEM_STAT or SEM_STAT_ANY operations to obtain information about all semaphore sets on the system.)

SEM_INFO

as for IPC_INFO.

SEM_STAT

the identifier of the semaphore set whose index was given in semid.

SEM_STAT_ANY

as for SEM_STAT.

All other cmd values return 0 on success.

On failure, semctl() returns -1 and sets errno to indicate the error.

## ERRORS
EACCES

The argument cmd has one of the values GETALL, GETPID, GETVAL, GETNCNT, GETZCNT, IPC_STAT, SEM_STAT, SEM_STAT_ANY, SETALL, or SETVAL and the calling process does not have the required permissions on the semaphore set and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

The address pointed to by arg.buf or arg.array isn't accessible.

EIDRM

The semaphore set was removed.

EINVAL

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

EPERM

The argument cmd has the value IPC_SET or IPC_RMID but the effective user ID of the calling process is not the creator (as found in sem_perm.cuid) or the owner (as found in sem_perm.uid) of the semaphore set, and the process does not have the CAP_SYS_ADMIN capability.

ERANGE

The argument cmd has the value SETALL or SETVAL and the value to which semval is to be set (for some semaphore of the set) is less than 0 or greater than the implementation limit SEMVMX.

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

POSIX.1 specifies the sem_nsems field of the semid_ds structure as having the type unsigned short, and the field is so defined on most other systems. It was also so defined on Linux 2.2 and earlier, but, since Linux 2.4, the field has the type unsigned long.

## NOTES
The IPC_INFO, SEM_STAT, and SEM_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.

Various fields in a struct semid_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.)

In some earlier versions of glibc, the semun union was defined in <sys/sem.h>, but POSIX.1 requires that the caller define this union. On versions of glibc where this union is not defined, the macro _SEM_SEMUN_UNDEFINED is defined in <sys/sem.h>.

The following system limit on semaphore sets affects a semctl() call:

SEMVMX

Maximum value for semval: implementation dependent (32767).

For greater portability, it is best to always call semctl() with four arguments.

### The sempid value
POSIX.1 defines sempid as the "process ID of [the] last operation" on a semaphore, and explicitly notes that this value is set by a successful semop(2) call, with the implication that no other interface affects the sempid value.

While some implementations conform to the behavior specified in POSIX.1, others do not. (The fault here probably lies with POSIX.1 inasmuch as it likely failed to capture the full range of existing implementation behaviors.) Various other implementations also update sempid for the other operations that update the value of a semaphore: the SETVAL and SETALL operations, as well as the semaphore adjustments performed on process termination as a consequence of the use of the SEM_UNDO flag (see semop(2)).

Linux also updates sempid for SETVAL operations and semaphore adjustments. However, somewhat inconsistently, up to and including Linux 4.5, the kernel did not update sempid for SETALL operations. This was rectified in Linux 4.6.

## EXAMPLES
See shmop(2).

## SEE ALSO
ipc(2), semget(2), semop(2), capabilities(7), sem_overview(7), sysvipc(7)


semget

package: man-pages

title: semget(2)

summary: get a System V semaphore set identifier

text:
# semget(2)

## NAME
semget - get a System V semaphore set identifier

## SYNOPSIS

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

int semget(key_t key, int nsems, int semflg);

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

A new set of nsems semaphores is created if key has the value IPC_PRIVATE or if no existing semaphore set is associated with key and IPC_CREAT is specified in semflg.

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

Upon creation, the least significant 9 bits of the argument semflg define the permissions (for owner, group, and others) for the semaphore set. These bits have the same format, and the same meaning, as the mode argument of open(2) (though the execute permissions are not meaningful for semaphores, and write permissions mean permission to alter semaphore values).

When creating a new semaphore set, semget() initializes the set's associated data structure, semid_ds (see semctl(2)), as follows:

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

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

- The least significant 9 bits of sem_perm.mode are set to the least significant 9 bits of semflg.

- sem_nsems is set to the value of nsems.

- sem_otime is set to 0.

- sem_ctime is set to the current time.

The argument nsems can be 0 (a don't care) when a semaphore set is not being created. Otherwise, nsems must be greater than 0 and less than or equal to the maximum number of semaphores per semaphore set (SEMMSL).

If the semaphore set already exists, the permissions are verified.

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

## ERRORS
EACCES

A semaphore set exists for key, but the calling process does not have permission to access the set, 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 semflg, but a semaphore set already exists for key.

EINVAL

nsems is less than 0 or greater than the limit on the number of semaphores per semaphore set (SEMMSL).

EINVAL

A semaphore set corresponding to key already exists, but nsems is larger than the number of semaphores in that set.

ENOENT

No semaphore set exists for key and semflg did not specify IPC_CREAT.

ENOMEM

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

ENOSPC

A semaphore set has to be created but the system limit for the maximum number of semaphore sets (SEMMNI), or the system wide maximum number of semaphores (SEMMNS), would be exceeded.

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

## 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 semflg and creates a new semaphore set (on success).

### Semaphore initialization
The values of the semaphores in a newly created set are indeterminate. (POSIX.1-2001 and POSIX.1-2008 are explicit on this point, although POSIX.1-2008 notes that a future version of the standard may require an implementation to initialize the semaphores to 0.) Although Linux, like many other implementations, initializes the semaphore values to 0, a portable application cannot rely on this: it should explicitly initialize the semaphores to the desired values.

Initialization can be done using semctl(2) SETVAL or SETALL operation. Where multiple peers do not know who will be the first to initialize the set, checking for a nonzero sem_otime in the associated data structure retrieved by a semctl(2) IPC_STAT operation can be used to avoid races.

### Semaphore limits
The following limits on semaphore set resources affect the semget() call:

SEMMNI

System-wide limit on the number of semaphore sets. On Linux systems before version 3.19, the default value for this limit was 128. Since Linux 3.19, the default value is 32,000. On Linux, this limit can be read and modified via the fourth field of /proc/sys/kernel/sem.

SEMMSL

Maximum number of semaphores per semaphore ID. On Linux systems before version 3.19, the default value for this limit was 250. Since Linux 3.19, the default value is 32,000. On Linux, this limit can be read and modified via the first field of /proc/sys/kernel/sem.

SEMMNS

System-wide limit on the number of semaphores: policy dependent (on Linux, this limit can be read and modified via the second field of /proc/sys/kernel/sem). Note that the number of semaphores system-wide is also limited by the product of SEMMSL and SEMMNI.

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

## EXAMPLES
The program shown below uses semget() to create a new semaphore set or retrieve the ID of an existing set. It generates the key for semget() using ftok(3). The first two command-line arguments are used as the pathname and proj_id arguments for ftok(3). The third command-line argument is an integer that specifies the nsems argument for semget(). Command-line options can be used to specify the IPC_CREAT (-c) and IPC_EXCL (-x) flags for the call to semget(). The usage of this program is demonstrated below.

We first create two files that will be used to generate keys using ftok(3), create two semaphore sets using those files, and then list the sets using ipcs(1):

```
$ touch mykey mykey2
$ ./t_semget -c mykey p 1
ID = 9
$ ./t_semget -c mykey2 p 2
ID = 10
$ ipcs -s
------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0x7004136d 9          mtk        600        1
0x70041368 10         mtk        600        2
```

Next, we demonstrate that when semctl(2) is given the same key (as generated by the same arguments to ftok(3)), it returns the ID of the already existing semaphore set:

```
$ ./t_semget -c mykey p 1
ID = 9
```

Finally, we demonstrate the kind of collision that can occur when ftok(3) is given different pathname arguments that have the same inode number:

```
$ ln mykey link
$ ls -i1 link mykey
2233197 link
2233197 mykey
$ ./t_semget link p 1       # Generates same key as 'mykey'
ID = 9
```

### Program source

```
/* t_semget.c

   Licensed under GNU General Public License v2 or later.
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void
usage(const char *pname)
{

    fprintf(stderr, "Usage: %s [-cx] pathname proj-id num-sems\n",

            pname);

    fprintf(stderr, "    -c           Use IPC_CREAT flag\n");

    fprintf(stderr, "    -x           Use IPC_EXCL flag\n");

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

    int semid, nsems, flags, opt;

    key_t key;

    flags = 0;

    while ((opt = getopt(argc, argv, "cx")) != -1) {

        switch (opt) {

        case 'c': flags |= IPC_CREAT;   break;

        case 'x': flags |= IPC_EXCL;    break;

        default:  usage(argv[0]);

        }

    }

    if (argc != optind + 3)

        usage(argv[0]);

    key = ftok(argv[optind], argv[optind + 1][0]);

    if (key == -1) {

        perror("ftok");

        exit(EXIT_FAILURE);

    }

    nsems = atoi(argv[optind + 2]);

    semid = semget(key, nsems, flags | 0600);

    if (semid == -1) {

        perror("semget");

        exit(EXIT_FAILURE);

    }

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

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
semctl(2), semop(2), ftok(3), capabilities(7), sem_overview(7), sysvipc(7)


semop

title: semop(2)

summary: System V semaphore operations

text:
# semop(2)

## NAME
semop, semtimedop - System V semaphore operations

## SYNOPSIS

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

```
int semop(int semid, struct sembuf *sops, size_t nsops);
int semtimedop(int semid, struct sembuf *sops, size_t nsops,
               const struct timespec *timeout);
```

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

semtimedop():

```
    _GNU_SOURCE
```

## DESCRIPTION
Each semaphore in a System V semaphore set has the following associated values:

```
unsigned short  semval;   /* semaphore value */
unsigned short  semzcnt;  /* # waiting for zero */
unsigned short  semncnt;  /* # waiting for increase */
pid_t           sempid;   /* PID of process that last
```

semop() performs operations on selected semaphores in the set indicated by semid. Each of the nsops elements in the array pointed to by sops is a structure that specifies an operation to be performed on a single semaphore. The elements of this structure are of type struct sembuf, containing the following members:

```
unsigned short sem_num;  /* semaphore number */
short          sem_op;   /* semaphore operation */
short          sem_flg;  /* operation flags */
```

Flags recognized in sem_flg are IPC_NOWAIT and SEM_UNDO. If an operation specifies SEM_UNDO, it will be automatically undone when the process terminates.

The set of operations contained in sops is performed in array order, and atomically, that is, the operations are performed either as a complete unit, or not at all. The behavior of the system call if not all operations can be performed immediately depends on the presence of the IPC_NOWAIT flag in the individual sem_flg fields, as noted below.

Each operation is performed on the sem_num-th semaphore of the semaphore set, where the first semaphore of the set is numbered 0. There are three types of operation, distinguished by the value of sem_op.

If sem_op is a positive integer, the operation adds this value to the semaphore value (semval). Furthermore, if SEM_UNDO is specified for this operation, the system subtracts the value sem_op from the semaphore adjustment (semadj) value for this semaphore. This operation can always proceed—it never forces a thread to wait. The calling process must have alter permission on the semaphore set.

If sem_op is zero, the process must have read permission on the semaphore set. This is a "wait-for-zero" operation: if semval is zero, the operation can immediately proceed. Otherwise, if IPC_NOWAIT is specified in sem_flg, semop() fails with errno set to EAGAIN (and none of the operations in sops is performed). Otherwise, semzcnt (the count of threads waiting until this semaphore's value becomes zero) is incremented by one and the thread sleeps until one of the following occurs:

- semval becomes 0, at which time the value of semzcnt is decremented.

- The semaphore set is removed: semop() fails, with errno set to EIDRM.

- The calling thread catches a signal: the value of semzcnt is decremented and semop() fails, with errno set to EINTR.

If sem_op is less than zero, the process must have alter permission on the semaphore set. If semval is greater than or equal to the absolute value of sem_op, the operation can proceed immediately: the absolute value of sem_op is subtracted from semval, and, if SEM_UNDO is specified for this operation, the system adds the absolute value of sem_op to the semaphore adjustment (semadj) value for this semaphore. If the absolute value of sem_op is greater than semval, and IPC_NOWAIT is specified in sem_flg, semop() fails, with errno set to EAGAIN (and none of the operations in sops is performed). Otherwise, semncnt (the counter of threads waiting for this semaphore's value to increase) is incremented by one and the thread sleeps until one of the following occurs:

- semval becomes greater than or equal to the absolute value of sem_op: the operation now proceeds, as described above.

- The semaphore set is removed from the system: semop() fails, with errno set to EIDRM.

- The calling thread catches a signal: the value of semncnt is decremented and semop() fails, with errno set to EINTR.

On successful completion, the sempid value for each semaphore specified in the array pointed to by sops is set to the caller's process ID. In addition, the sem_otime is set to the current time.

### semtimedop()
semtimedop() behaves identically to semop() except that in those cases where the calling thread would sleep, the duration of that sleep is limited by the amount of elapsed time specified by the timespec structure whose address is passed in the timeout argument. (This sleep interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the interval may overrun by a small amount.) If the specified time limit has been reached, semtimedop() fails with errno set to EAGAIN (and none of the operations in sops is performed). If the timeout argument is NULL, then semtimedop() behaves exactly like semop().

Note that if semtimedop() is interrupted by a signal, causing the call to fail with the error EINTR, the contents of timeout are left unchanged.

## RETURN VALUE
On success, semop() and semtimedop() return 0. On failure, they return -1, and set errno to indicate the error.

## ERRORS
E2BIG

The argument nsops is greater than SEMOPM, the maximum number of operations allowed per system call.

EACCES

The calling process does not have the permissions required to perform the specified semaphore operations, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EAGAIN

An operation could not proceed immediately and either IPC_NOWAIT was specified in sem_flg or the time limit specified in timeout expired.

EFAULT

An address specified in either the sops or the timeout argument isn't accessible.

EFBIG

For some operation the value of sem_num is less than 0 or greater than or equal to the number of semaphores in the set.

EIDRM

The semaphore set was removed.

EINTR

While blocked in this system call, the thread caught a signal; see signal(7).

EINVAL

The semaphore set doesn't exist, or semid is less than zero, or nsops has a nonpositive value.

ENOMEM

The sem_flg of some operation specified SEM_UNDO and the system does not have enough memory to allocate the undo structure.

ERANGE

For some operation sem_op+semval is greater than SEMVMX, the implementation dependent maximum value for semval.

## VERSIONS
semtimedop() first appeared in Linux 2.5.52, and was subsequently backported into kernel 2.4.22. Glibc support for semtimedop() first appeared in version 2.3.3.

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

## NOTES
The sem_undo structures of a process aren't inherited by the child produced by fork(2), but they are inherited across an execve(2) system call.

semop() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.

A semaphore adjustment (semadj) value is a per-process, per-semaphore integer that is the negated sum of all operations performed on a semaphore specifying the SEM_UNDO flag. Each process has a list of semadj values—one value for each semaphore on which it has operated using SEM_UNDO. When a process terminates, each of its per-semaphore semadj values is added to the corresponding semaphore, thus undoing the effect of that process's operations on the semaphore (but see BUGS below). When a semaphore's value is directly set using the SETVAL or SETALL request to semctl(2), the corresponding semadj values in all processes are cleared. The clone(2) CLONE_SYSVSEM flag allows more than one process to share a semadj list; see clone(2) for details.

The semval, sempid, semzcnt, and semnct values for a semaphore can all be retrieved using appropriate semctl(2) calls.

### Semaphore limits
The following limits on semaphore set resources affect the semop() call:

SEMOPM

Maximum number of operations allowed for one semop() call. Before Linux 3.19, the default value for this limit was 32. Since Linux 3.19, the default value is 500. On Linux, this limit can be read and modified via the third field of /proc/sys/kernel/sem. Note: this limit should not be raised above 1000, because of the risk of that semop() fails due to kernel memory fragmentation when allocating memory to copy the sops array.

SEMVMX

Maximum allowable value for semval: implementation dependent (32767).

The implementation has no intrinsic limits for the adjust on exit maximum value (SEMAEM), the system wide maximum number of undo structures (SEMMNU) and the per-process maximum number of undo entries system parameters.

## BUGS
When a process terminates, its set of associated semadj structures is used to undo the effect of all of the semaphore operations it performed with the SEM_UNDO flag. This raises a difficulty: if one (or more) of these semaphore adjustments would result in an attempt to decrease a semaphore's value below zero, what should an implementation do? One possible approach would be to block until all the semaphore adjustments could be performed. This is however undesirable since it could force process termination to block for arbitrarily long periods. Another possibility is that such semaphore adjustments could be ignored altogether (somewhat analogously to failing when IPC_NOWAIT is specified for a semaphore operation). Linux adopts a third approach: decreasing the semaphore value as far as possible (i.e., to zero) and allowing process termination to proceed immediately.

In kernels 2.6.x, x <= 10, there is a bug that in some circumstances prevents a thread that is waiting for a semaphore value to become zero from being woken up when the value does actually become zero. This bug is fixed in kernel 2.6.11.

## EXAMPLES
The following code segment uses semop() to atomically wait for the value of semaphore 0 to become zero, and then increment the semaphore value by one.

```
struct sembuf sops[2];
int semid;
/* Code to set semid omitted */
sops[0].sem_num = 0;        /* Operate on semaphore 0 */
sops[0].sem_op = 0;         /* Wait for value to equal 0 */
sops[0].sem_flg = 0;
sops[1].sem_num = 0;        /* Operate on semaphore 0 */
sops[1].sem_op = 1;         /* Increment value by one */
sops[1].sem_flg = 0;
if (semop(semid, sops, 2) == -1) {

    perror("semop");

    exit(EXIT_FAILURE);
}
```

A further example of the use of semop() can be found in shmop(2).

## SEE ALSO
clone(2), semctl(2), semget(2), sigaction(2), capabilities(7), sem_overview(7), sysvipc(7), time(7)


send

title: send(2)

summary: send a message on a socket

text:
# send(2)

## NAME
send, sendto, sendmsg - send a message on a socket

## SYNOPSIS

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

```
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen);
ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
```

## DESCRIPTION
The system calls send(), sendto(), and sendmsg() are used to transmit a message to another socket.

The send() call may be used only when the socket is in a connected state (so that the intended recipient is known). The only difference between send() and write(2) is the presence of flags. With a zero flags argument, send() is equivalent to write(2). Also, the following call

send(sockfd, buf, len, flags);

is equivalent to

sendto(sockfd, buf, len, flags, NULL, 0);

The argument sockfd is the file descriptor of the sending socket.

If sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket, the arguments dest_addr and addrlen are ignored (and the error EISCONN may be returned when they are not NULL and 0), and the error ENOTCONN is returned when the socket was not actually connected. Otherwise, the address of the target is given by dest_addr with addrlen specifying its size. For sendmsg(), the address of the target is given by msg.msg_name, with msg.msg_namelen specifying its size.

For send() and sendto(), the message is found in buf and has length len. For sendmsg(), the message is pointed to by the elements of the array msg.msg_iov. The sendmsg() call also allows sending ancillary data (also known as control information).

If the message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is returned, and the message is not transmitted.

No indication of failure to deliver is implicit in a send(). Locally detected errors are indicated by a return value of -1.

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in nonblocking I/O mode. In nonblocking mode it would fail with the error EAGAIN or EWOULDBLOCK in this case. The select(2) call may be used to determine when it is possible to send more data.

### The flags argument
The flags argument is the bitwise OR of zero or more of the following flags.

MSG_CONFIRM (since Linux 2.3.15)

Tell the link layer that forward progress happened: you got a successful reply from the other side. If the link layer doesn't get this it will regularly reprobe the neighbor (e.g., via a unicast ARP). Valid only on SOCK_DGRAM and SOCK_RAW sockets and currently implemented only for IPv4 and IPv6. See arp(7) for details.

MSG_DONTROUTE

Don't use a gateway to send out the packet, send to hosts only on directly connected networks. This is usually used only by diagnostic or routing programs. This is defined only for protocol families that route; packet sockets don't.

MSG_DONTWAIT (since Linux 2.2)

Enables nonblocking operation; if the operation would block, EAGAIN or EWOULDBLOCK is returned. This provides similar behavior to setting the O_NONBLOCK flag (via the fcntl(2) F_SETFL operation), but differs in that MSG_DONTWAIT is a per-call option, whereas O_NONBLOCK is a setting on the open file description (see open(2)), which will affect all threads in the calling process and as well as other processes that hold file descriptors referring to the same open file description.

MSG_EOR (since Linux 2.2)

Terminates a record (when this notion is supported, as for sockets of type SOCK_SEQPACKET).

MSG_MORE (since Linux 2.4.4)

The caller has more data to send. This flag is used with TCP sockets to obtain the same effect as the TCP_CORK socket option (see tcp(7)), with the difference that this flag can be set on a per-call basis.

Since Linux 2.6, this flag is also supported for UDP sockets, and informs the kernel to package all of the data sent in calls with this flag set into a single datagram which is transmitted only when a call is performed that does not specify this flag. (See also the UDP_CORK socket option described in udp(7).)

MSG_NOSIGNAL (since Linux 2.2)

Don't generate a SIGPIPE signal if the peer on a stream-oriented socket has closed the connection. The EPIPE error is still returned. This provides similar behavior to using sigaction(2) to ignore SIGPIPE, but, whereas MSG_NOSIGNAL is a per-call feature, ignoring SIGPIPE sets a process attribute that affects all threads in the process.

MSG_OOB

Sends out-of-band data on sockets that support this notion (e.g., of type SOCK_STREAM); the underlying protocol must also support out-of-band data.

### sendmsg()
The definition of the msghdr structure employed by sendmsg() is as follows:

```
struct msghdr {

    void         *msg_name;       /* Optional address */

    socklen_t     msg_namelen;    /* Size of address */

    struct iovec *msg_iov;        /* Scatter/gather array */

    size_t        msg_iovlen;     /* # elements in msg_iov */

    void         *msg_control;    /* Ancillary data, see below */

    size_t        msg_controllen; /* Ancillary data buffer len */

    int           msg_flags;      /* Flags (unused) */
};
```

The msg_name field is used on an unconnected socket to specify the target address for a datagram. It points to a buffer containing the address; the msg_namelen field should be set to the size of the address. For a connected socket, these fields should be specified as NULL and 0, respectively.

The msg_iov and msg_iovlen fields specify scatter-gather locations, as for writev(2).

You may send control information (ancillary data) using the msg_control and msg_controllen members. The maximum control buffer length the kernel can process is limited per socket by the value in /proc/sys/net/core/optmem_max; see socket(7). For further information on the use of ancillary data in various socket domains, see unix(7) and ip(7).

The msg_flags field is ignored.

## RETURN VALUE
On success, these calls return the number of bytes sent. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
These are some standard errors generated by the socket layer. Additional errors may be generated and returned from the underlying protocol modules; see their respective manual pages.

EACCES

(For UNIX domain sockets, which are identified by pathname) Write permission is denied on the destination socket file, or search permission is denied for one of the directories the path prefix. (See path_resolution(7).)

(For UDP sockets) An attempt was made to send to a network/broadcast address as though it was a unicast address.

EAGAIN or EWOULDBLOCK

The socket is marked nonblocking and the requested operation would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.

EAGAIN

(Internet domain datagram sockets) The socket referred to by sockfd had not previously been bound to an address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).

EALREADY

Another Fast Open is in progress.

EBADF

sockfd is not a valid open file descriptor.

ECONNRESET

Connection reset by peer.

EDESTADDRREQ

The socket is not connection-mode, and no peer address is set.

EFAULT

An invalid user space address was specified for an argument.

EINTR

A signal occurred before any data was transmitted; see signal(7).

EINVAL

Invalid argument passed.

EISCONN

The connection-mode socket was connected already but a recipient was specified. (Now either this error is returned, or the recipient specification is ignored.)

EMSGSIZE

The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible.

ENOBUFS

The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)

ENOMEM

No memory available.

ENOTCONN

The socket is not connected, and no target has been given.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

EOPNOTSUPP

Some bit in the flags argument is inappropriate for the socket type.

EPIPE

The local end has been shut down on a connection oriented socket. In this case, the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.

## CONFORMING TO
4.4BSD, SVr4, POSIX.1-2001. These interfaces first appeared in 4.2BSD.

POSIX.1-2001 describes only the MSG_OOB and MSG_EOR flags. POSIX.1-2008 adds a specification of MSG_NOSIGNAL. The MSG_CONFIRM flag is a Linux extension.

## NOTES
According to POSIX.1-2001, the msg_controllen field of the msghdr structure should be typed as socklen_t, and the msg_iovlen field should be typed as int, but glibc currently types both as size_t.

See sendmmsg(2) for information about a Linux-specific system call that can be used to transmit multiple datagrams in a single call.

## BUGS
Linux may return EPIPE instead of ENOTCONN.

## EXAMPLES
An example of the use of sendto() is shown in getaddrinfo(3).

## SEE ALSO
fcntl(2), getsockopt(2), recv(2), select(2), sendfile(2), sendmmsg(2), shutdown(2), socket(2), write(2), cmsg(3), ip(7), ipv6(7), socket(7), tcp(7), udp(7), unix(7)


sendfile

title: sendfile(2)

summary: transfer data between file descriptors

text:
# sendfile(2)

## NAME
sendfile - transfer data between file descriptors

## SYNOPSIS

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

```
ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
```

## DESCRIPTION
sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space.

in_fd should be a file descriptor opened for reading and out_fd should be a descriptor opened for writing.

If offset is not NULL, then it points to a variable holding the file offset from which sendfile() will start reading data from in_fd. When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read. If offset is not NULL, then sendfile() does not modify the file offset of in_fd; otherwise the file offset is adjusted to reflect the number of bytes read from in_fd.

If offset is NULL, then data will be read from in_fd starting at the file offset, and the file offset will be updated by the call.

count is the number of bytes to copy between the file descriptors.

The in_fd argument must correspond to a file which supports mmap(2)-like operations (i.e., it cannot be a socket).

In Linux kernels before 2.6.33, out_fd must refer to a socket. Since Linux 2.6.33 it can be any file. If it is a regular file, then sendfile() changes the file offset appropriately.

## RETURN VALUE
If the transfer was successful, the number of bytes written to out_fd is returned. Note that a successful call to sendfile() may write fewer bytes than requested; the caller should be prepared to retry the call if there were unsent bytes. See also NOTES.

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

## ERRORS
EAGAIN

Nonblocking I/O has been selected using O_NONBLOCK and the write would block.

EBADF

The input file was not opened for reading or the output file was not opened for writing.

EFAULT

Bad address.

EINVAL

Descriptor is not valid or locked, or an mmap(2)-like operation is not available for in_fd, or count is negative.

EINVAL

out_fd has the O_APPEND flag set. This is not currently supported by sendfile().

EIO

Unspecified error while reading from in_fd.

ENOMEM

Insufficient memory to read from in_fd.

EOVERFLOW

count is too large, the operation would result in exceeding the maximum size of either the input file or the output file.

ESPIPE

offset is not NULL but the input file is not seekable.

## VERSIONS
sendfile() first appeared in Linux 2.2. The include file <sys/sendfile.h> is present since glibc 2.1.

## CONFORMING TO
Not specified in POSIX.1-2001, nor in other standards.

Other UNIX systems implement sendfile() with different semantics and prototypes. It should not be used in portable programs.

## NOTES
sendfile() will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)

If you plan to use sendfile() for sending files to a TCP socket, but need to send some header data in front of the file contents, you will find it useful to employ the TCP_CORK option, described in tcp(7), to minimize the number of packets and to tune performance.

In Linux 2.4 and earlier, out_fd could also refer to a regular file; this possibility went away in the Linux 2.6.x kernel series, but was restored in Linux 2.6.33.

The original Linux sendfile() system call was not designed to handle large file offsets. Consequently, Linux 2.4 added sendfile64(), with a wider type for the offset argument. The glibc sendfile() wrapper function transparently deals with the kernel differences.

Applications may wish to fall back to read(2)/write(2) in the case where sendfile() fails with EINVAL or ENOSYS.

If out_fd refers to a socket or pipe with zero-copy support, callers must ensure the transferred portions of the file referred to by in_fd remain unmodified until the reader on the other end of out_fd has consumed the transferred data.

The Linux-specific splice(2) call supports transferring data between arbitrary file descriptors provided one (or both) of them is a pipe.

## SEE ALSO
copy_file_range(2), mmap(2), open(2), socket(2), splice(2)


sendmmsg

title: sendmmsg(2)

summary: send multiple messages on a socket

text:
# sendmmsg(2)

## NAME
sendmmsg - send multiple messages on a socket

## SYNOPSIS

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

```
int sendmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen,
             int flags);
```

## DESCRIPTION
The sendmmsg() system call is an extension of sendmsg(2) that allows the caller to transmit multiple messages on a socket using a single system call. (This has performance benefits for some applications.)

The sockfd argument is the file descriptor of the socket on which data is to be transmitted.

The msgvec argument is a pointer to an array of mmsghdr structures. The size of this array is specified in vlen.

The mmsghdr structure is defined in <sys/socket.h> as:

```
struct mmsghdr {

    struct msghdr msg_hdr;  /* Message header */

    unsigned int  msg_len;  /* Number of bytes transmitted */
};
```

The msg_hdr field is a msghdr structure, as described in sendmsg(2). The msg_len field is used to return the number of bytes sent from the message in msg_hdr (i.e., the same as the return value from a single sendmsg(2) call).

The flags argument contains flags ORed together. The flags are the same as for sendmsg(2).

A blocking sendmmsg() call blocks until vlen messages have been sent. A nonblocking call sends as many messages as possible (up to the limit specified by vlen) and returns immediately.

On return from sendmmsg(), the msg_len fields of successive elements of msgvec are updated to contain the number of bytes transmitted from the corresponding msg_hdr. The return value of the call indicates the number of elements of msgvec that have been updated.

## RETURN VALUE
On success, sendmmsg() returns the number of messages sent from msgvec; if this is less than vlen, the caller can retry with a further sendmmsg() call to send the remaining messages.

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

## ERRORS
Errors are as for sendmsg(2). An error is returned only if no datagrams could be sent. See also BUGS.

## VERSIONS
The sendmmsg() system call was added in Linux 3.0. Support in glibc was added in version 2.14.

## CONFORMING TO
sendmmsg() is Linux-specific.

## NOTES
The value specified in vlen is capped to UIO_MAXIOV (1024).

## BUGS
If an error occurs after at least one message has been sent, the call succeeds, and returns the number of messages sent. The error code is lost. The caller can retry the transmission, starting at the first failed message, but there is no guarantee that, if an error is returned, it will be the same as the one that was lost on the previous call.

## EXAMPLES
The example below uses sendmmsg() to send onetwo and three in two distinct UDP datagrams using one system call. The contents of the first datagram originates from a pair of buffers.

```
#define _GNU_SOURCE
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int
main(void)
{

    int sockfd;

    struct sockaddr_in addr;

    struct mmsghdr msg[2];

    struct iovec msg1[2], msg2;

    int retval;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd == -1) {

        perror("socket()");

        exit(EXIT_FAILURE);

    }

    addr.sin_family = AF_INET;

    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    addr.sin_port = htons(1234);

    if (connect(sockfd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {

        perror("connect()");

        exit(EXIT_FAILURE);

    }

    memset(msg1, 0, sizeof(msg1));

    msg1[0].iov_base = "one";

    msg1[0].iov_len = 3;

    msg1[1].iov_base = "two";

    msg1[1].iov_len = 3;

    memset(&msg2, 0, sizeof(msg2));

    msg2.iov_base = "three";

    msg2.iov_len = 5;

    memset(msg, 0, sizeof(msg));

    msg[0].msg_hdr.msg_iov = msg1;

    msg[0].msg_hdr.msg_iovlen = 2;

    msg[1].msg_hdr.msg_iov = &msg2;

    msg[1].msg_hdr.msg_iovlen = 1;

    retval = sendmmsg(sockfd, msg, 2, 0);

    if (retval == -1)

        perror("sendmmsg()");

    else

        printf("%d messages sent\n", retval);

    exit(0);
}
```

## SEE ALSO
recvmmsg(2), sendmsg(2), socket(2), socket(7)


title: set_mempolicy(2)

text:
# set_mempolicy(2)

## NAME
set_mempolicy - set default NUMA memory policy for a thread and its children

## SYNOPSIS

```
#include <numaif.h>
```

```
long set_mempolicy(int mode, const unsigned long *nodemask,
                   unsigned long maxnode);
```

```
Link with -lnuma.
```

## DESCRIPTION
set_mempolicy() sets the NUMA memory policy of the calling thread, which consists of a policy mode and zero or more nodes, to the values specified by the mode, nodemask, and maxnode arguments.

A NUMA machine has different memory controllers with different distances to specific CPUs. The memory policy defines from which node memory is allocated for the thread.

This system call defines the default policy for the thread. The thread policy governs allocation of pages in the process's address space outside of memory ranges controlled by a more specific policy set by mbind(2). The thread default policy also controls allocation of any pages for memory-mapped files mapped using the mmap(2) call with the MAP_PRIVATE flag and that are only read (loaded) from by the thread and of memory-mapped files mapped using the mmap(2) call with the MAP_SHARED flag, regardless of the access type. The policy is applied only when a new page is allocated for the thread. For anonymous memory this is when the page is first touched by the thread.

The mode argument must specify one of MPOL_DEFAULT, MPOL_BIND, MPOL_INTERLEAVE, MPOL_PREFERRED, or MPOL_LOCAL (which are described in detail below). All modes except MPOL_DEFAULT require the caller to specify the node or nodes to which the mode applies, via the nodemask argument.

The mode argument may also include an optional mode flag. The supported mode flags are:

MPOL_F_NUMA_BALANCING (since Linux 5.12)

When mode is MPOL_BIND, enable the kernel NUMA balancing for the task if it is supported by the kernel. If the flag isn't supported by the kernel, or is used with mode other than MPOL_BIND, -1 is returned and errno is set to EINVAL.

MPOL_F_RELATIVE_NODES (since Linux 2.6.26)

A nonempty nodemask specifies node IDs that are relative to the set of node IDs allowed by the process's current cpuset.

MPOL_F_STATIC_NODES (since Linux 2.6.26)

A nonempty nodemask specifies physical node IDs. Linux will not remap the nodemask when the process moves to a different cpuset context, nor when the set of nodes allowed by the process's current cpuset context changes.

nodemask points to a bit mask of node IDs that contains up to maxnode bits. The bit mask size is rounded to the next multiple of sizeof(unsigned long), but the kernel will use bits only up to maxnode. A NULL value of nodemask or a maxnode value of zero specifies the empty set of nodes. If the value of maxnode is zero, the nodemask argument is ignored.

Where a nodemask is required, it must contain at least one node that is on-line, allowed by the process's current cpuset context, (unless the MPOL_F_STATIC_NODES mode flag is specified), and contains memory. If the MPOL_F_STATIC_NODES is set in mode and a required nodemask contains no nodes that are allowed by the process's current cpuset context, the memory policy reverts to local allocation. This effectively overrides the specified policy until the process's cpuset context includes one or more of the nodes specified by nodemask.

The mode argument must include one of the following values:

MPOL_DEFAULT

This mode specifies that any nondefault thread memory policy be removed, so that the memory policy "falls back" to the system default policy. The system default policy is "local allocation"—that is, allocate memory on the node of the CPU that triggered the allocation. nodemask must be specified as NULL. If the "local node" contains no free memory, the system will attempt to allocate memory from a "near by" node.

MPOL_BIND

This mode defines a strict policy that restricts memory allocation to the nodes specified in nodemask. If nodemask specifies more than one node, page allocations will come from the node with the lowest numeric node ID first, until that node contains no free memory. Allocations will then come from the node with the next highest node ID specified in nodemask and so forth, until none of the specified nodes contain free memory. Pages will not be allocated from any node not specified in the nodemask.

MPOL_INTERLEAVE

This mode interleaves page allocations across the nodes specified in nodemask in numeric node ID order. This optimizes for bandwidth instead of latency by spreading out pages and memory accesses to those pages across multiple nodes. However, accesses to a single page will still be limited to the memory bandwidth of a single node.

MPOL_PREFERRED

This mode sets the preferred node for allocation. The kernel will try to allocate pages from this node first and fall back to "near by" nodes if the preferred node is low on free memory. If nodemask specifies more than one node ID, the first node in the mask will be selected as the preferred node. If the nodemask and maxnode arguments specify the empty set, then the policy specifies "local allocation" (like the system default policy discussed above).

MPOL_LOCAL (since Linux 3.8)

This mode specifies "local allocation"; the memory is allocated on the node of the CPU that triggered the allocation (the "local node"). The nodemask and maxnode arguments must specify the empty set. If the "local node" is low on free memory, the kernel will try to allocate memory from other nodes. The kernel will allocate memory from the "local node" whenever memory for this node is available. If the "local node" is not allowed by the process's current cpuset context, the kernel will try to allocate memory from other nodes. The kernel will allocate memory from the "local node" whenever it becomes allowed by the process's current cpuset context.

The thread memory policy is preserved across an execve(2), and is inherited by child threads created using fork(2) or clone(2).

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

## ERRORS
EFAULT

Part of all of the memory range specified by nodemask and maxnode points outside your accessible address space.

EINVAL

mode is invalid. Or, mode is MPOL_DEFAULT and nodemask is nonempty, or mode is MPOL_BIND or MPOL_INTERLEAVE and nodemask is empty. Or, maxnode specifies more than a page worth of bits. Or, nodemask specifies one or more node IDs that are greater than the maximum supported node ID. Or, none of the node IDs specified by nodemask are on-line and allowed by the process's current cpuset context, or none of the specified nodes contain memory. Or, the mode argument specified both MPOL_F_STATIC_NODES and MPOL_F_RELATIVE_NODES. Or, the MPOL_F_NUMA_BALANCING isn't supported by the kernel, or is used with mode other than MPOL_BIND.

ENOMEM

Insufficient kernel memory was available.

## VERSIONS
The set_mempolicy() system call was added to the Linux kernel in version 2.6.7.

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

## NOTES
Memory policy is not remembered if the page is swapped out. When such a page is paged back in, it will use the policy of the thread or memory range that is in effect at the time the page is allocated.

For information on library support, see numa(7).

## SEE ALSO
get_mempolicy(2), getcpu(2), mbind(2), mmap(2), numa(3), cpuset(7), numa(7), numactl(8)


title: set_thread_area(2)

text:
# set_thread_area(2)

## NAME
get_thread_area, set_thread_area - manipulate thread-local storage information

## SYNOPSIS

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

```
#if defined __i386__ || defined __x86_64__
# include <asm/ldt.h>        /* Definition of struct user_desc */
```

```
int syscall(SYS_get_thread_area, struct user_desc *u_info);
int syscall(SYS_set_thread_area, struct user_desc *u_info);
```

```
#elif defined __m68k__
```

```
int syscall(SYS_get_thread_area);
int syscall(SYS_set_thread_area, unsigned long tp);
```

```
#elif defined __mips__
```

```
int syscall(SYS_set_thread_area, unsigned long addr);
```

```
#endif
```

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

## DESCRIPTION
These calls provide architecture-specific support for a thread-local storage implementation. At the moment, set_thread_area() is available on m68k, MIPS, and x86 (both 32-bit and 64-bit variants); get_thread_area() is available on m68k and x86.

On m68k and MIPS, set_thread_area() allows storing an arbitrary pointer (provided in the tp argument on m68k and in the addr argument on MIPS) in the kernel data structure associated with the calling thread; this pointer can later be retrieved using get_thread_area() (see also NOTES for information regarding obtaining the thread pointer on MIPS).

On x86, Linux dedicates three global descriptor table (GDT) entries for thread-local storage. For more information about the GDT, see the Intel Software Developer's Manual or the AMD Architecture Programming Manual.

Both of these system calls take an argument that is a pointer to a structure of the following type:

```
struct user_desc {

    unsigned int  entry_number;

    unsigned int  base_addr;

    unsigned int  limit;

    unsigned int  seg_32bit:1;

    unsigned int  contents:2;

    unsigned int  read_exec_only:1;

    unsigned int  limit_in_pages:1;

    unsigned int  seg_not_present:1;

    unsigned int  useable:1;
#ifdef __x86_64__

    unsigned int  lm:1;
#endif
};
```

get_thread_area() reads the GDT entry indicated by u_info->entry_number and fills in the rest of the fields in u_info.

set_thread_area() sets a TLS entry in the GDT.

The TLS array entry set by set_thread_area() corresponds to the value of u_info->entry_number passed in by the user. If this value is in bounds, set_thread_area() writes the TLS descriptor pointed to by u_info into the thread's TLS array.

When set_thread_area() is passed an entry_number of -1, it searches for a free TLS entry. If set_thread_area() finds a free TLS entry, the value of u_info->entry_number is set upon return to show which entry was changed.

A user_desc is considered "empty" if read_exec_only and seg_not_present are set to 1 and all of the other fields are 0. If an "empty" descriptor is passed to set_thread_area(), the corresponding TLS entry will be cleared. See BUGS for additional details.

Since Linux 3.19, set_thread_area() cannot be used to write non-present segments, 16-bit segments, or code segments, although clearing a segment is still acceptable.

## RETURN VALUE
On x86, these system calls return 0 on success, and -1 on failure, with errno set to indicate the error.

On MIPS and m68k, set_thread_area() always returns 0. On m68k, get_thread_area() returns the thread area pointer value (previously set via set_thread_area()).

## ERRORS
EFAULT

u_info is an invalid pointer.

EINVAL

u_info->entry_number is out of bounds.

ENOSYS

get_thread_area() or set_thread_area() was invoked as a 64-bit system call.

ESRCH

(set_thread_area()) A free TLS entry could not be located.

## VERSIONS
set_thread_area() first appeared in Linux 2.5.29. get_thread_area() first appeared in Linux 2.5.32.

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

## NOTES
These system calls are generally intended for use only by threading libraries.

arch_prctl(2) can interfere with set_thread_area() on x86. See arch_prctl(2) for more details. This is not normally a problem, as arch_prctl(2) is normally used only by 64-bit programs.

On MIPS, the current value of the thread area pointer can be obtained using the instruction:

```
rdhwr dest, $29
```

This instruction traps and is handled by kernel.

## BUGS
On 64-bit kernels before Linux 3.19, one of the padding bits in user_desc, if set, would prevent the descriptor from being considered empty (see modify_ldt(2)). As a result, the only reliable way to clear a TLS entry is to use memset(3) to zero the entire user_desc structure, including padding bits, and then to set the read_exec_only and seg_not_present bits. On Linux 3.19, a user_desc consisting entirely of zeros except for entry_number will also be interpreted as a request to clear a TLS entry, but this behaved differently on older kernels.

Prior to Linux 3.19, the DS and ES segment registers must not reference TLS entries.

## SEE ALSO
arch_prctl(2), modify_ldt(2), ptrace(2) (PTRACE_GET_THREAD_AREA and PTRACE_SET_THREAD_AREA)


title: set_tid_address(2)

summary: set pointer to thread ID

text:
# set_tid_address(2)

## NAME
set_tid_address - set pointer to thread ID

## SYNOPSIS

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

```
pid_t syscall(SYS_set_tid_address, int *tidptr);
```

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

## DESCRIPTION
For each thread, the kernel maintains two attributes (addresses) called set_child_tid and clear_child_tid. These two attributes contain the value NULL by default.

set_child_tid

If a thread is started using clone(2) with the CLONE_CHILD_SETTID flag, set_child_tid is set to the value passed in the ctid argument of that system call.

When set_child_tid is set, the very first thing the new thread does is to write its thread ID at this address.

clear_child_tid

If a thread is started using clone(2) with the CLONE_CHILD_CLEARTID flag, clear_child_tid is set to the value passed in the ctid argument of that system call.

The system call set_tid_address() sets the clear_child_tid value for the calling thread to tidptr.

When a thread whose clear_child_tid is not NULL terminates, then, if the thread is sharing memory with other threads, then 0 is written at the address specified in clear_child_tid and the kernel performs the following operation:

futex(clear_child_tid, FUTEX_WAKE, 1, NULL, NULL, 0);

The effect of this operation is to wake a single thread that is performing a futex wait on the memory location. Errors from the futex wake operation are ignored.

## RETURN VALUE
set_tid_address() always returns the caller's thread ID.

## ERRORS
set_tid_address() always succeeds.

## VERSIONS
This call is present since Linux 2.5.48. Details as given here are valid since Linux 2.5.49.

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

## SEE ALSO
clone(2), futex(2), gettid(2)


seteuid

title: seteuid(2)

summary: set effective user or group ID

text:
# seteuid(2)

## NAME
seteuid, setegid - set effective user or group ID

## SYNOPSIS

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

```
int seteuid(uid_t euid);
int setegid(gid_t egid);
```

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

seteuid(), setegid():

```
    _POSIX_C_SOURCE >= 200112L

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

## DESCRIPTION
seteuid() sets the effective user ID of the calling process. Unprivileged processes may only set the effective user ID to the real user ID, the effective user ID or the saved set-user-ID.

Precisely the same holds for setegid() 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 seteuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from seteuid().

## ERRORS
EINVAL

The target user or group ID is not valid in this user namespace.

EPERM

In the case of seteuid(): the calling process is not privileged (does not have the CAP_SETUID capability in its user namespace) and euid does not match the current real user ID, current effective user ID, or current saved set-user-ID.

In the case of setegid(): the calling process is not privileged (does not have the CAP_SETGID capability in its user namespace) and egid does not match the current real group ID, current effective group ID, or current saved set-group-ID.

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

## NOTES
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). On an arbitrary system one should check _POSIX_SAVED_IDS.

Under glibc 2.0, seteuid(euid) is equivalent to setreuid(-1, euid) and hence may change the saved set-user-ID. Under glibc 2.1 and later, it is equivalent to setresuid(-1, euid, -1) and hence does not change the saved set-user-ID. Analogous remarks hold for setegid(), with the difference that the change in implementation from setregid(-1, egid) to setresgid(-1, egid, -1) occurred in glibc 2.2 or 2.3 (depending on the hardware architecture).

According to POSIX.1, seteuid() (setegid()) need not permit euid (egid) to be the same value as the current effective user (group) ID, and some implementations do not permit this.

### C library/kernel differences
On Linux, seteuid() and setegid() are implemented as library functions that call, respectively, setreuid(2) and setregid(2).

## SEE ALSO
geteuid(2), setresuid(2), setreuid(2), setuid(2), capabilities(7), credentials(7), user_namespaces(7)


setfsgid

title: setfsgid(2)

text:
# setfsgid(2)

## NAME
setfsgid - set group identity used for filesystem checks

## SYNOPSIS

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

```
int setfsgid(gid_t fsgid);
```

## DESCRIPTION
On Linux, a process has both a filesystem group ID and an effective group ID. The (Linux-specific) filesystem group ID is used for permissions checking when accessing filesystem objects, while the effective group ID is used for some other kinds of permissions checks (see credentials(7)).

Normally, the value of the process's filesystem group ID is the same as the value of its effective group ID. This is so, because whenever a process's effective group ID is changed, the kernel also changes the filesystem group ID to be the same as the new value of the effective group ID. A process can cause the value of its filesystem group ID to diverge from its effective group ID by using setfsgid() to change its filesystem group ID to the value given in fsgid.

setfsgid() will succeed only if the caller is the superuser or if fsgid matches either the caller's real group ID, effective group ID, saved set-group-ID, or current the filesystem user ID.

## RETURN VALUE
On both success and failure, this call returns the previous filesystem group ID of the caller.

## VERSIONS
This system call is present in Linux since version 1.2.

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

## NOTES
The filesystem group ID concept and the setfsgid() system call were invented for historical reasons that are no longer applicable on modern Linux kernels. See setfsuid(2) for a discussion of why the use of both setfsuid(2) and setfsgid() is nowadays unneeded.

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

### C library/kernel differences
In glibc 2.15 and earlier, when the wrapper for this system call determines that the argument can't be passed to the kernel without integer truncation (because the kernel is old and does not support 32-bit group IDs), it will return -1 and set errno to EINVAL without attempting the system call.

## BUGS
No error indications of any kind are returned to the caller, and the fact that both successful and unsuccessful calls return the same value makes it impossible to directly determine whether the call succeeded or failed. Instead, the caller must resort to looking at the return value from a further call such as setfsgid(-1) (which will always fail), in order to determine if a preceding call to setfsgid() changed the filesystem group ID. At the very least, EPERM should be returned when the call fails (because the caller lacks the CAP_SETGID capability).

## SEE ALSO
kill(2), setfsuid(2), capabilities(7), credentials(7)


setfsuid

title: setfsuid(2)

text:
# setfsuid(2)

## NAME
setfsuid - set user identity used for filesystem checks

## SYNOPSIS

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

```
int setfsuid(uid_t fsuid);
```

## DESCRIPTION
On Linux, a process has both a filesystem user ID and an effective user ID. The (Linux-specific) filesystem user ID is used for permissions checking when accessing filesystem objects, while the effective user ID is used for various other kinds of permissions checks (see credentials(7)).

Normally, the value of the process's filesystem user ID is the same as the value of its effective user ID. This is so, because whenever a process's effective user ID is changed, the kernel also changes the filesystem user ID to be the same as the new value of the effective user ID. A process can cause the value of its filesystem user ID to diverge from its effective user ID by using setfsuid() to change its filesystem user ID to the value given in fsuid.

Explicit calls to setfsuid() and setfsgid(2) are (were) usually used only by programs such as the Linux NFS server that need to change what user and group ID is used for file access without a corresponding change in the real and effective user and group IDs. A change in the normal user IDs for a program such as the NFS server is (was) a security hole that can expose it to unwanted signals. (However, this issue is historical; see below.)

setfsuid() will succeed only if the caller is the superuser or if fsuid matches either the caller's real user ID, effective user ID, saved set-user-ID, or current filesystem user ID.

## RETURN VALUE
On both success and failure, this call returns the previous filesystem user ID of the caller.

## VERSIONS
This system call is present in Linux since version 1.2.

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

## NOTES
At the time when this system call was introduced, one process could send a signal to another process with the same effective user ID. This meant that if a privileged process changed its effective user ID for the purpose of file permission checking, then it could become vulnerable to receiving signals sent by another (unprivileged) process with the same user ID. The filesystem user ID attribute was thus added to allow a process to change its user ID for the purposes of file permission checking without at the same time becoming vulnerable to receiving unwanted signals. Since Linux 2.0, signal permission handling is different (see kill(2)), with the result that a process can change its effective user ID without being vulnerable to receiving signals from unwanted processes. Thus, setfsuid() is nowadays unneeded and should be avoided in new applications (likewise for setfsgid(2)).

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

### C library/kernel differences
In glibc 2.15 and earlier, when the wrapper for this system call determines that the argument can't be passed to the kernel without integer truncation (because the kernel is old and does not support 32-bit user IDs), it will return -1 and set errno to EINVAL without attempting the system call.

## BUGS
No error indications of any kind are returned to the caller, and the fact that both successful and unsuccessful calls return the same value makes it impossible to directly determine whether the call succeeded or failed. Instead, the caller must resort to looking at the return value from a further call such as setfsuid(-1) (which will always fail), in order to determine if a preceding call to setfsuid() changed the filesystem user ID. At the very least, EPERM should be returned when the call fails (because the caller lacks the CAP_SETUID capability).

## SEE ALSO
kill(2), setfsgid(2), capabilities(7), credentials(7)


setgid

title: setgid(2)

summary: set group identity

text:
# setgid(2)

## NAME
setgid - set group identity

## SYNOPSIS

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

```
int setgid(gid_t gid);
```

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

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

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

## ERRORS
EINVAL

The group ID specified in gid is not valid in this user namespace.

EPERM

The calling process is not privileged (does not have the CAP_SETGID capability in its user namespace), and gid does not match the real group ID or saved set-group-ID of the calling process.

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

## NOTES
The original Linux setgid() system call supported only 16-bit group IDs. Subsequently, Linux 2.4 added setgid32() supporting 32-bit IDs. The glibc setgid() wrapper function transparently deals with the variation 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 the one for setgid()) 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), setegid(2), setregid(2), capabilities(7), credentials(7), user_namespaces(7)


setns

title: setns(2)

summary: reassociate thread with a namespace

text:
# setns(2)

## NAME
setns - reassociate thread with a namespace

## SYNOPSIS

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

```
int setns(int fd, int nstype);
```

## DESCRIPTION
The setns() system call allows the calling thread to move into different namespaces. The fd argument is one of the following:

- a file descriptor referring to one of the magic links in a /proc/[pid]/ns/ directory (or a bind mount to such a link);

- a PID file descriptor (see pidfd_open(2)).

The nstype argument is interpreted differently in each case.

### fd refers to a /proc/[pid]/ns/ link
If fd refers to a /proc/[pid]/ns/ link, then setns() reassociates the calling thread with the namespace associated with that link, subject to any constraints imposed by the nstype argument. In this usage, each call to setns() changes just one of the caller's namespace memberships.

The nstype argument specifies which type of namespace the calling thread may be reassociated with. This argument can have one of the following values:

0

Allow any type of namespace to be joined.

CLONE_NEWCGROUP (since Linux 4.6)

fd must refer to a cgroup namespace.

CLONE_NEWIPC (since Linux 3.0)

fd must refer to an IPC namespace.

CLONE_NEWNET (since Linux 3.0)

fd must refer to a network namespace.

CLONE_NEWNS (since Linux 3.8)

fd must refer to a mount namespace.

CLONE_NEWPID (since Linux 3.8)

fd must refer to a descendant PID namespace.

CLONE_NEWTIME (since Linux 5.8)

fd must refer to a time namespace.

CLONE_NEWUSER (since Linux 3.8)

fd must refer to a user namespace.

CLONE_NEWUTS (since Linux 3.0)

fd must refer to a UTS namespace.

Specifying nstype as 0 suffices if the caller knows (or does not care) what type of namespace is referred to by fd. Specifying a nonzero value for nstype is useful if the caller does not know what type of namespace is referred to by fd and wants to ensure that the namespace is of a particular type. (The caller might not know the type of the namespace referred to by fd if the file descriptor was opened by another process and, for example, passed to the caller via a UNIX domain socket.)

### fd is a PID file descriptor
Since Linux 5.8, fd may refer to a PID file descriptor obtained from pidfd_open(2) or clone(2). In this usage, setns() atomically moves the calling thread into one or more of the same namespaces as the thread referred to by fd.

The nstype argument is a bit mask specified by ORing together one or more of the CLONE_NEW* namespace constants listed above. The caller is moved into each of the target thread's namespaces that is specified in nstype; the caller's memberships in the remaining namespaces are left unchanged.

For example, the following code would move the caller into the same user, network, and UTS namespaces as PID 1234, but would leave the caller's other namespace memberships unchanged:

```
int fd = pidfd_open(1234, 0);
setns(fd, CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWUTS);
```

### Details for specific namespace types
Note the following details and restrictions when reassociating with specific namespace types:

User namespaces

A process reassociating itself with a user namespace must have the CAP_SYS_ADMIN capability in the target user namespace. (This necessarily implies that it is only possible to join a descendant user namespace.) Upon successfully joining a user namespace, a process is granted all capabilities in that namespace, regardless of its user and group IDs.

A multithreaded process may not change user namespace with setns().

It is not permitted to use setns() to reenter the caller's current user namespace. This prevents a caller that has dropped capabilities from regaining those capabilities via a call to setns().

For security reasons, a process can't join a new user namespace if it is sharing filesystem-related attributes (the attributes whose sharing is controlled by the clone(2) CLONE_FS flag) with another process.

For further details on user namespaces, see user_namespaces(7).

Mount namespaces

Changing the mount namespace requires that the caller possess both CAP_SYS_CHROOT and CAP_SYS_ADMIN capabilities in its own user namespace and CAP_SYS_ADMIN in the user namespace that owns the target mount namespace.

A process can't join a new mount namespace if it is sharing filesystem-related attributes (the attributes whose sharing is controlled by the clone(2) CLONE_FS flag) with another process.

See user_namespaces(7) for details on the interaction of user namespaces and mount namespaces.

PID namespaces

In order to reassociate itself with a new PID namespace, the caller must have the CAP_SYS_ADMIN capability both in its own user namespace and in the user namespace that owns the target PID namespace.

Reassociating the PID namespace has somewhat different from other namespace types. Reassociating the calling thread with a PID namespace changes only the PID namespace that subsequently created child processes of the caller will be placed in; it does not change the PID namespace of the caller itself.

Reassociating with a PID namespace is allowed only if the target PID namespace is a descendant (child, grandchild, etc.) of, or is the same as, the current PID namespace of the caller.

For further details on PID namespaces, see pid_namespaces(7).

Cgroup namespaces

In order to reassociate itself with a new cgroup namespace, the caller must have the CAP_SYS_ADMIN capability both in its own user namespace and in the user namespace that owns the target cgroup namespace.

Using setns() to change the caller's cgroup namespace does not change the caller's cgroup memberships.

Network, IPC, time, and UTS namespaces

In order to reassociate itself with a new network, IPC, time, or UTS namespace, the caller must have the CAP_SYS_ADMIN capability both in its own user namespace and in the user namespace that owns the target namespace.

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

## ERRORS
EBADF

fd is not a valid file descriptor.

EINVAL

fd refers to a namespace whose type does not match that specified in nstype.

EINVAL

There is problem with reassociating the thread with the specified namespace.

EINVAL

The caller tried to join an ancestor (parent, grandparent, and so on) PID namespace.

EINVAL

The caller attempted to join the user namespace in which it is already a member.

EINVAL

The caller shares filesystem (CLONE_FS) state (in particular, the root directory) with other processes and tried to join a new user namespace.

EINVAL

The caller is multithreaded and tried to join a new user namespace.

EINVAL

fd is a PID file descriptor and nstype is invalid (e.g., it is 0).

ENOMEM

Cannot allocate sufficient memory to change the specified namespace.

EPERM

The calling thread did not have the required capability for this operation.

ESRCH

fd is a PID file descriptor but the process it refers to no longer exists (i.e., it has terminated and been waited on).

## VERSIONS
The setns() system call first appeared in Linux in kernel 3.0; library support was added to glibc in version 2.14.

## CONFORMING TO
The setns() system call is Linux-specific.

## NOTES
For further information on the /proc/[pid]/ns/ magic links, see namespaces(7).

Not all of the attributes that can be shared when a new thread is created using clone(2) can be changed using setns().

## EXAMPLES
The program below takes two or more arguments. The first argument specifies the pathname of a namespace file in an existing /proc/[pid]/ns/ directory. The remaining arguments specify a command and its arguments. The program opens the namespace file, joins that namespace using setns(), and executes the specified command inside that namespace.

The following shell session demonstrates the use of this program (compiled as a binary named ns_exec) in conjunction with the CLONE_NEWUTS example program in the clone(2) man page (complied as a binary named newuts).

We begin by executing the example program in clone(2) in the background. That program creates a child in a separate UTS namespace. The child changes the hostname in its namespace, and then both processes display the hostnames in their UTS namespaces, so that we can see that they are different.

```
$ su                   # Need privilege for namespace operations
Password:
# ./newuts bizarro &
[1] 3549
clone() returned 3550
uts.nodename in child:  bizarro
uts.nodename in parent: antero
# uname -n             # Verify hostname in the shell
antero
```

We then run the program shown below, using it to execute a shell. Inside that shell, we verify that the hostname is the one set by the child created by the first program:

```
# ./ns_exec /proc/3550/ns/uts /bin/bash
# uname -n             # Executed in shell started by ns_exec
bizarro
```

### Program source

```
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \

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

    int fd;

    if (argc < 3) {

        fprintf(stderr, "%s /proc/PID/ns/FILE cmd args...\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    /* Get file descriptor for namespace; the file descriptor is opened

       with O_CLOEXEC so as to ensure that it is not inherited by the

       program that is later executed. */

    fd = open(argv[1], O_RDONLY | O_CLOEXEC);

    if (fd == -1)

        errExit("open");

    if (setns(fd, 0) == -1)       /* Join that namespace */

        errExit("setns");

    execvp(argv[2], &argv[2]);    /* Execute a command in namespace */

    errExit("execvp");
}
```

## SEE ALSO
nsenter(1), clone(2), fork(2), unshare(2), vfork(2), namespaces(7), unix(7)


setpgid

title: setpgid(2)

summary: set/get process group

text:
# setpgid(2)

## NAME
setpgid, getpgid, setpgrp, getpgrp - set/get process group

## SYNOPSIS

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

```
int setpgid(pid_t pid, pid_t pgid);
pid_t getpgid(pid_t pid);
```

```
pid_t getpgrp(void);                 /* POSIX.1 version */
pid_t getpgrp(pid_t pid);            /* BSD version */
```

```
int setpgrp(void);                   /* System V version */
int setpgrp(pid_t pid, pid_t pgid);  /* BSD version */
```

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

getpgid():

```
    _XOPEN_SOURCE >= 500

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

setpgrp() (POSIX.1):

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

        || /* Glibc <= 2.19: */ _SVID_SOURCE
```

setpgrp() (BSD), getpgrp() (BSD):

```
    [These are available only before glibc 2.19]

    _BSD_SOURCE &&

        ! (_POSIX_SOURCE || _POSIX_C_SOURCE || _XOPEN_SOURCE

            || _GNU_SOURCE || _SVID_SOURCE)
```

## DESCRIPTION
All of these interfaces are available on Linux, and are used for getting and setting the process group ID (PGID) of a process. The preferred, POSIX.1-specified ways of doing this are: getpgrp(void), for retrieving the calling process's PGID; and setpgid(), for setting a process's PGID.

setpgid() sets the PGID of the process specified by pid to pgid. If pid is zero, then the process ID of the calling process is used. If pgid is zero, then the PGID of the process specified by pid is made the same as its process ID. If setpgid() is used to move a process from one process group to another (as is done by some shells when creating pipelines), both process groups must be part of the same session (see setsid(2) and credentials(7)). In this case, the pgid specifies an existing process group to be joined and the session ID of that group must match the session ID of the joining process.

The POSIX.1 version of getpgrp(), which takes no arguments, returns the PGID of the calling process.

getpgid() returns the PGID of the process specified by pid. If pid is zero, the process ID of the calling process is used. (Retrieving the PGID of a process other than the caller is rarely necessary, and the POSIX.1 getpgrp() is preferred for that task.)

The System V-style setpgrp(), which takes no arguments, is equivalent to setpgid(0, 0).

The BSD-specific setpgrp() call, which takes arguments pid and pgid, is a wrapper function that calls

setpgid(pid, pgid)

Since glibc 2.19, the BSD-specific setpgrp() function is no longer exposed by <unistd.h>; calls should be replaced with the setpgid() call shown above.

The BSD-specific getpgrp() call, which takes a single pid argument, is a wrapper function that calls

getpgid(pid)

Since glibc 2.19, the BSD-specific getpgrp() function is no longer exposed by <unistd.h>; calls should be replaced with calls to the POSIX.1 getpgrp() which takes no arguments (if the intent is to obtain the caller's PGID), or with the getpgid() call shown above.

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

The POSIX.1 getpgrp() always returns the PGID of the caller.

getpgid(), and the BSD-specific getpgrp() return a process group on success. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

An attempt was made to change the process group ID of one of the children of the calling process and the child had already performed an execve(2) (setpgid(), setpgrp()).

EINVAL

pgid is less than 0 (setpgid(), setpgrp()).

EPERM

An attempt was made to move a process into a process group in a different session, or to change the process group ID of one of the children of the calling process and the child was in a different session, or to change the process group ID of a session leader (setpgid(), setpgrp()).

ESRCH

For getpgid(): pid does not match any process. For setpgid(): pid is not the calling process and not a child of the calling process.

## CONFORMING TO
setpgid() and the version of getpgrp() with no arguments conform to POSIX.1-2001.

POSIX.1-2001 also specifies getpgid() and the version of setpgrp() that takes no arguments. (POSIX.1-2008 marks this setpgrp() specification as obsolete.)

The version of getpgrp() with one argument and the version of setpgrp() that takes two arguments derive from 4.2BSD, and are not specified by POSIX.1.

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

Each process group is a member of a session and each process is a member of the session of which its process group is a member. (See credentials(7).)

A session can have a controlling terminal. At any time, one (and only one) of the process groups in the session can be the foreground process group for the terminal; the remaining process groups are in the background. If a signal is generated from the terminal (e.g., typing the interrupt key to generate SIGINT), that signal is sent to the foreground process group. (See termios(3) for a description of the characters that generate signals.) Only the foreground process group may read(2) from the terminal; if a background process group tries to read(2) from the terminal, then the group is sent a SIGTTIN signal, which suspends it. The tcgetpgrp(3) and tcsetpgrp(3) functions are used to get/set the foreground process group of the controlling terminal.

The setpgid() and getpgrp() calls are used by programs such as bash(1) to create process groups in order to implement shell job control.

If the termination of a process causes a process group to become orphaned, and if any member of the newly orphaned process group is stopped, then a SIGHUP signal followed by a SIGCONT signal will be sent to each process in the newly orphaned process group. An orphaned process group is one in which the parent of every member of process group is either itself also a member of the process group or is a member of a process group in a different session (see also credentials(7)).

## SEE ALSO
getuid(2), setsid(2), tcgetpgrp(3), tcsetpgrp(3), termios(3), credentials(7)


setresuid

title: setresuid(2)

text:
# setresuid(2)

## NAME
setresuid, setresgid - set real, effective, and saved user or group ID

## SYNOPSIS

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

```
int setresuid(uid_t ruid, uid_t euid, uid_t suid);
int setresgid(gid_t rgid, gid_t egid, gid_t sgid);
```

## DESCRIPTION
setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the calling process.

An unprivileged process may change its real UID, effective UID, and saved set-user-ID, each to one of: the current real UID, the current effective UID, or the current saved set-user-ID.

A privileged process (on Linux, one having the CAP_SETUID capability) may set its real UID, effective UID, and saved set-user-ID to arbitrary values.

If one of the arguments equals -1, the corresponding value is not changed.

Regardless of what changes are made to the real UID, effective UID, and saved set-user-ID, the filesystem UID is always set to the same value as the (possibly new) effective UID.

Completely analogously, setresgid() sets the real GID, effective GID, and saved set-group-ID of the calling process (and always modifies the filesystem GID to be the same as the effective GID), with the same restrictions for unprivileged processes.

## 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 setresuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from setresuid().

## 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 (did not have the necessary capability in its user namespace) and tried to change the IDs to values that are not permitted. For setresuid(), the necessary capability is CAP_SETUID; for setresgid(), it is CAP_SETGID.

## VERSIONS
These calls are available under Linux since Linux 2.1.44.

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

## NOTES
Under HP-UX and FreeBSD, the prototype is found in <unistd.h>. Under Linux, the prototype is provided by glibc since version 2.3.2.

The original Linux setresuid() and setresgid() system calls supported only 16-bit user and group IDs. Subsequently, Linux 2.4 added setresuid32() and setresgid32(), supporting 32-bit IDs. The glibc setresuid() and setresgid() 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 setresuid() and setresgid()) 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
getresuid(2), getuid(2), setfsgid(2), setfsuid(2), setreuid(2), setuid(2), capabilities(7), credentials(7), user_namespaces(7)