signal

title: signal(7)

summary: overview of signals

text:
# signal(7)

## NAME
signal - overview of signals

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

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

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

Term

Default action is to terminate the process.

Ign

Default action is to ignore the signal.

Core

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

Stop

Default action is to stop the process.

Cont

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

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

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

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

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

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

raise(3)

Sends a signal to the calling thread.

kill(2)

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

pidfd_send_signal(2)

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

killpg(3)

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

pthread_kill(3)

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

tgkill(2)

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

sigqueue(3)

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

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

pause(2)

Suspends execution until any signal is caught.

sigsuspend(2)

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

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

•

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

•

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

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

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

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

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

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

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

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

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

(1)

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

(1.1)

The signal is removed from the set of pending signals.

(1.2)

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

(1.3)

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

•

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

•

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

•

the thread's current signal mask;

•

the thread's alternate signal stack settings.

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

(1.4)

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

(2)

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

(3)

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

(4)

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

(5)

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

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

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

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

Signal

Standard

Action

Comment

SIGABRT

P1990

Core

Abort signal from abort(3)

SIGALRM

P1990

Term

Timer signal from alarm(2)

SIGBUS

P2001

Core

Bus error (bad memory access)

SIGCHLD

P1990

Ign

Child stopped or terminated

SIGCLD

-

Ign

A synonym for SIGCHLD

SIGCONT

P1990

Cont

Continue if stopped

SIGEMT

-

Term

Emulator trap

SIGFPE

P1990

Core

Floating-point exception

SIGHUP

P1990

Term

Hangup detected on controlling terminal

or death of controlling process

SIGILL

P1990

Core

Illegal Instruction

SIGINFO

-

A synonym for SIGPWR

SIGINT

P1990

Term

Interrupt from keyboard

SIGIO

-

Term

I/O now possible (4.2BSD)

SIGIOT

-

Core

IOT trap. A synonym for SIGABRT

SIGKILL

P1990

Term

Kill signal

SIGLOST

-

Term

File lock lost (unused)

SIGPIPE

P1990

Term

Broken pipe: write to pipe with no

readers; see pipe(7)

SIGPOLL

P2001

Term

Pollable event (Sys V);

synonym for SIGIO

SIGPROF

P2001

Term

Profiling timer expired

SIGPWR

-

Term

Power failure (System V)

SIGQUIT

P1990

Core

Quit from keyboard

SIGSEGV

P1990

Core

Invalid memory reference

SIGSTKFLT

-

Term

Stack fault on coprocessor (unused)

SIGSTOP

P1990

Stop

Stop process

SIGTSTP

P1990

Stop

Stop typed at terminal

SIGSYS

P2001

Core

Bad system call (SVr4);

see also seccomp(2)

SIGTERM

P1990

Term

Termination signal

SIGTRAP

P2001

Core

Trace/breakpoint trap

SIGTTIN

P1990

Stop

Terminal input for background process

SIGTTOU

P1990

Stop

Terminal output for background process

SIGUNUSED

-

Core

Synonymous with SIGSYS

SIGURG

P2001

Ign

Urgent condition on socket (4.2BSD)

SIGUSR1

P1990

Term

User-defined signal 1

SIGUSR2

P1990

Term

User-defined signal 2

SIGVTALRM

P2001

Term

Virtual alarm clock (4.2BSD)

SIGXCPU

P2001

Core

CPU time limit exceeded (4.2BSD);

see setrlimit(2)

SIGXFSZ

P2001

Core

File size limit exceeded (4.2BSD);

see setrlimit(2)

SIGWINCH

-

Ign

Window resize signal (4.3BSD, Sun)

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

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

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

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

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

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

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

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

Signal

x86/ARM

Alpha/

MIPS

PARISC

Notes

most others

SPARC

SIGHUP

1

1

1

1

SIGINT

2

2

2

2

SIGQUIT

3

3

3

3

SIGILL

4

4

4

4

SIGTRAP

5

5

5

5

SIGABRT

6

6

6

6

SIGIOT

6

6

6

6

SIGBUS

7

10

10

10

SIGEMT

-

7

7

-

SIGFPE

8

8

8

8

SIGKILL

9

9

9

9

SIGUSR1

10

30

16

16

SIGSEGV

11

11

11

11

SIGUSR2

12

31

17

17

SIGPIPE

13

13

13

13

SIGALRM

14

14

14

14

SIGTERM

15

15

15

15

SIGSTKFLT

16

-

-

7

SIGCHLD

17

20

18

18

SIGCLD

-

-

18

-

SIGCONT

18

19

25

26

SIGSTOP

19

17

23

24

SIGTSTP

20

18

24

25

SIGTTIN

21

21

26

27

SIGTTOU

22

22

27

28

SIGURG

23

16

21

29

SIGXCPU

24

24

30

12

SIGXFSZ

25

25

31

30

SIGVTALRM

26

26

28

20

SIGPROF

27

27

29

21

SIGWINCH

28

28

20

23

SIGIO

29

23

22

22

SIGPOLL

Same as SIGIO

SIGPWR

30

29/-

19

19

SIGINFO

-

29/-

-

-

SIGLOST

-

-/29

-

-

SIGSYS

31

12

12

31

SIGUNUSED

31

-

-

31

Note the following:

•

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

•

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

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

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

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

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

Real-time signals are distinguished by the following:

•

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

•

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

•

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

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

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

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

Linux 2.0 and earlier

Linux 2.2 and later

sigaction(2)

rt_sigaction(2)

sigpending(2)

rt_sigpending(2)

sigprocmask(2)

rt_sigprocmask(2)

sigreturn(2)

rt_sigreturn(2)

sigsuspend(2)

rt_sigsuspend(2)

sigtimedwait(2)

rt_sigtimedwait(2)

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

•

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

•

the call fails with the error EINTR.

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

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

•

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

•

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

•

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

•

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

•

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

•

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

•

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

•

getrandom(2).

•

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

•

futex(2) FUTEX_WAIT_BITSET.

•

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

•

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

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

•

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

•

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

•

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

•

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

•

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

•

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

•

io_getevents(2).

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

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

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

The Linux interfaces that display this behavior are:

•

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

•

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

•

epoll_wait(2), epoll_pwait(2).

•

semop(2), semtimedop(2).

•

sigtimedwait(2), sigwaitinfo(2).

•

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

•

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

•

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

•

Linux 2.4 and earlier: nanosleep(2).

## STANDARDS
POSIX.1, except as noted.

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

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

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

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

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

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


signal-safety

package: man-pages

title: signal-safety(7)

summary: async-signal-safe functions

text:
# signal-safety(7)

## NAME
signal-safety - async-signal-safe functions

## DESCRIPTION
An async-signal-safe function is one that can be safely called from within a signal handler. Many functions are not async-signal-safe. In particular, nonreentrant functions are generally unsafe to call from a signal handler.

The kinds of issues that render a function unsafe can be quickly understood when one considers the implementation of the stdio library, all of whose functions are not async-signal-safe.

When performing buffered I/O on a file, the stdio functions must maintain a statically allocated data buffer along with associated counters and indexes (or pointers) that record the amount of data and the current position in the buffer. Suppose that the main program is in the middle of a call to a stdio function such as printf(3) where the buffer and associated variables have been partially updated. If, at that moment, the program is interrupted by a signal handler that also calls printf(3), then the second call to printf(3) will operate on inconsistent data, with unpredictable results.

To avoid problems with unsafe functions, there are two possible choices:

(a)

Ensure that (1) the signal handler calls only async-signal-safe functions, and (2) the signal handler itself is reentrant with respect to global variables in the main program.

(b)

Block signal delivery in the main program when calling functions that are unsafe or operating on global data that is also accessed by the signal handler.

Generally, the second choice is difficult in programs of any complexity, so the first choice is taken.

POSIX.1 specifies a set of functions that an implementation must make async-signal-safe. (An implementation may provide safe implementations of additional functions, but this is not required by the standard and other implementations may not provide the same guarantees.)

In general, a function is async-signal-safe either because it is reentrant or because it is atomic with respect to signals (i.e., its execution can't be interrupted by a signal handler).

The set of functions required to be async-signal-safe by POSIX.1 is shown in the following table. The functions not otherwise noted were required to be async-signal-safe in POSIX.1-2001; the table details changes in the subsequent standards.

Function

Notes

abort(3)

Added in POSIX.1-2001 TC1

accept(2)

access(2)

aio_error(3)

aio_return(3)

aio_suspend(3)

See notes below

alarm(2)

bind(2)

cfgetispeed(3)

cfgetospeed(3)

cfsetispeed(3)

cfsetospeed(3)

chdir(2)

chmod(2)

chown(2)

clock_gettime(2)

close(2)

connect(2)

creat(2)

dup(2)

dup2(2)

execl(3)

Added in POSIX.1-2008; see notes below

execle(3)

See notes below

execv(3)

Added in POSIX.1-2008

execve(2)

_exit(2)

_Exit(2)

faccessat(2)

Added in POSIX.1-2008

fchdir(2)

Added in POSIX.1-2008 TC1

fchmod(2)

fchmodat(2)

Added in POSIX.1-2008

fchown(2)

fchownat(2)

Added in POSIX.1-2008

fcntl(2)

fdatasync(2)

fexecve(3)

Added in POSIX.1-2008

ffs(3)

Added in POSIX.1-2008 TC2

fork(2)

See notes below

fstat(2)

fstatat(2)

Added in POSIX.1-2008

fsync(2)

ftruncate(2)

futimens(3)

Added in POSIX.1-2008

getegid(2)

geteuid(2)

getgid(2)

getgroups(2)

getpeername(2)

getpgrp(2)

getpid(2)

getppid(2)

getsockname(2)

getsockopt(2)

getuid(2)

htonl(3)

Added in POSIX.1-2008 TC2

htons(3)

Added in POSIX.1-2008 TC2

kill(2)

link(2)

linkat(2)

Added in POSIX.1-2008

listen(2)

longjmp(3)

Added in POSIX.1-2008 TC2; see notes below

lseek(2)

lstat(2)

memccpy(3)

Added in POSIX.1-2008 TC2

memchr(3)

Added in POSIX.1-2008 TC2

memcmp(3)

Added in POSIX.1-2008 TC2

memcpy(3)

Added in POSIX.1-2008 TC2

memmove(3)

Added in POSIX.1-2008 TC2

memset(3)

Added in POSIX.1-2008 TC2

mkdir(2)

mkdirat(2)

Added in POSIX.1-2008

mkfifo(3)

mkfifoat(3)

Added in POSIX.1-2008

mknod(2)

Added in POSIX.1-2008

mknodat(2)

Added in POSIX.1-2008

ntohl(3)

Added in POSIX.1-2008 TC2

ntohs(3)

Added in POSIX.1-2008 TC2

open(2)

openat(2)

Added in POSIX.1-2008

pause(2)

pipe(2)

poll(2)

posix_trace_event(3)

pselect(2)

pthread_kill(3)

Added in POSIX.1-2008 TC1

pthread_self(3)

Added in POSIX.1-2008 TC1

pthread_sigmask(3)

Added in POSIX.1-2008 TC1

raise(3)

read(2)

readlink(2)

readlinkat(2)

Added in POSIX.1-2008

recv(2)

recvfrom(2)

recvmsg(2)

rename(2)

renameat(2)

Added in POSIX.1-2008

rmdir(2)

select(2)

sem_post(3)

send(2)

sendmsg(2)

sendto(2)

setgid(2)

setpgid(2)

setsid(2)

setsockopt(2)

setuid(2)

shutdown(2)

sigaction(2)

sigaddset(3)

sigdelset(3)

sigemptyset(3)

sigfillset(3)

sigismember(3)

siglongjmp(3)

Added in POSIX.1-2008 TC2; see notes below

signal(2)

sigpause(3)

sigpending(2)

sigprocmask(2)

sigqueue(2)

sigset(3)

sigsuspend(2)

sleep(3)

sockatmark(3)

Added in POSIX.1-2001 TC2

socket(2)

socketpair(2)

stat(2)

stpcpy(3)

Added in POSIX.1-2008 TC2

stpncpy(3)

Added in POSIX.1-2008 TC2

strcat(3)

Added in POSIX.1-2008 TC2

strchr(3)

Added in POSIX.1-2008 TC2

strcmp(3)

Added in POSIX.1-2008 TC2

strcpy(3)

Added in POSIX.1-2008 TC2

strcspn(3)

Added in POSIX.1-2008 TC2

strlen(3)

Added in POSIX.1-2008 TC2

strncat(3)

Added in POSIX.1-2008 TC2

strncmp(3)

Added in POSIX.1-2008 TC2

strncpy(3)

Added in POSIX.1-2008 TC2

strnlen(3)

Added in POSIX.1-2008 TC2

strpbrk(3)

Added in POSIX.1-2008 TC2

strrchr(3)

Added in POSIX.1-2008 TC2

strspn(3)

Added in POSIX.1-2008 TC2

strstr(3)

Added in POSIX.1-2008 TC2

strtok_r(3)

Added in POSIX.1-2008 TC2

symlink(2)

symlinkat(2)

Added in POSIX.1-2008

tcdrain(3)

tcflow(3)

tcflush(3)

tcgetattr(3)

tcgetpgrp(3)

tcsendbreak(3)

tcsetattr(3)

tcsetpgrp(3)

time(2)

timer_getoverrun(2)

timer_gettime(2)

timer_settime(2)

times(2)

umask(2)

uname(2)

unlink(2)

unlinkat(2)

Added in POSIX.1-2008

utime(2)

utimensat(2)

Added in POSIX.1-2008

utimes(2)

Added in POSIX.1-2008

wait(2)

waitpid(2)

wcpcpy(3)

Added in POSIX.1-2008 TC2

wcpncpy(3)

Added in POSIX.1-2008 TC2

wcscat(3)

Added in POSIX.1-2008 TC2

wcschr(3)

Added in POSIX.1-2008 TC2

wcscmp(3)

Added in POSIX.1-2008 TC2

wcscpy(3)

Added in POSIX.1-2008 TC2

wcscspn(3)

Added in POSIX.1-2008 TC2

wcslen(3)

Added in POSIX.1-2008 TC2

wcsncat(3)

Added in POSIX.1-2008 TC2

wcsncmp(3)

Added in POSIX.1-2008 TC2

wcsncpy(3)

Added in POSIX.1-2008 TC2

wcsnlen(3)

Added in POSIX.1-2008 TC2

wcspbrk(3)

Added in POSIX.1-2008 TC2

wcsrchr(3)

Added in POSIX.1-2008 TC2

wcsspn(3)

Added in POSIX.1-2008 TC2

wcsstr(3)

Added in POSIX.1-2008 TC2

wcstok(3)

Added in POSIX.1-2008 TC2

wmemchr(3)

Added in POSIX.1-2008 TC2

wmemcmp(3)

Added in POSIX.1-2008 TC2

wmemcpy(3)

Added in POSIX.1-2008 TC2

wmemmove(3)

Added in POSIX.1-2008 TC2

wmemset(3)

Added in POSIX.1-2008 TC2

write(2)

Notes:

•

POSIX.1-2001 and POSIX.1-2001 TC2 required the functions fpathconf(3), pathconf(3), and sysconf(3) to be async-signal-safe, but this requirement was removed in POSIX.1-2008.

•

If a signal handler interrupts the execution of an unsafe function, and the handler terminates via a call to longjmp(3) or siglongjmp(3) and the program subsequently calls an unsafe function, then the behavior of the program is undefined.

•

POSIX.1-2001 TC1 clarified that if an application calls fork(2) from a signal handler and any of the fork handlers registered by pthread_atfork(3) calls a function that is not async-signal-safe, the behavior is undefined. A future revision of the standard is likely to remove fork(2) from the list of async-signal-safe functions.

•

Asynchronous signal handlers that call functions which are cancelation points and nest over regions of deferred cancelation may trigger cancelation whose behavior is as if asynchronous cancelation had occurred and may cause application state to become inconsistent.

### errno
Fetching and setting the value of errno is async-signal-safe provided that the signal handler saves errno on entry and restores its value before returning.

### Deviations in the GNU C library
The following known deviations from the standard occur in the GNU C library:

•

Before glibc 2.24, execl(3) and execle(3) employed realloc(3) internally and were consequently not async-signal-safe. This was fixed in glibc 2.24.

•

The glibc implementation of aio_suspend(3) is not async-signal-safe because it uses pthread_mutex_lock(3) internally.

## SEE ALSO
sigaction(2), signal(7), standards(7)

branch: sisyphus


title: sock_diag(7)

summary: obtaining information about sockets

text:
# sock_diag(7)

## NAME
sock_diag - obtaining information about sockets

## SYNOPSIS

```
#include <sys/socket.h>
#include <linux/sock_diag.h>
#include <linux/unix_diag.h> /* for UNIX domain sockets */
#include <linux/inet_diag.h> /* for IPv4 and IPv6 sockets */
```

```
diag_socket = socket(AF_NETLINK, socket_type, NETLINK_SOCK_DIAG);
```

## DESCRIPTION
The sock_diag netlink subsystem provides a mechanism for obtaining information about sockets of various address families from the kernel. This subsystem can be used to obtain information about individual sockets or request a list of sockets.

In the request, the caller can specify additional information it would like to obtain about the socket, for example, memory information or information specific to the address family.

When requesting a list of sockets, the caller can specify filters that would be applied by the kernel to select a subset of sockets to report. For now, there is only the ability to filter sockets by state (connected, listening, and so on.)

Note that sock_diag reports only those sockets that have a name; that is, either sockets bound explicitly with bind(2) or sockets that were automatically bound to an address (e.g., by connect(2)). This is the same set of sockets that is available via /proc/net/unix, /proc/net/tcp, /proc/net/udp, and so on.

### Request
The request starts with a struct nlmsghdr header described in netlink(7) with nlmsg_type field set to SOCK_DIAG_BY_FAMILY. It is followed by a header specific to the address family that starts with a common part shared by all address families:

```
struct sock_diag_req {

    __u8 sdiag_family;

    __u8 sdiag_protocol;
};
```

The fields of this structure are as follows:

sdiag_family

An address family. It should be set to the appropriate AF_* constant.

sdiag_protocol

Depends on sdiag_family. It should be set to the appropriate IPPROTO_* constant for AF_INET and AF_INET6, and to 0 otherwise.

If the nlmsg_flags field of the struct nlmsghdr header has the NLM_F_DUMP flag set, it means that a list of sockets is being requested; otherwise it is a query about an individual socket.

### Response
The response starts with a struct nlmsghdr header and is followed by an array of objects specific to the address family. The array is to be accessed with the standard NLMSG_* macros from the netlink(3) API.

Each object is the NLA (netlink attributes) list that is to be accessed with the RTA_* macros from rtnetlink(3) API.

### UNIX domain sockets
For UNIX domain sockets the request is represented in the following structure:

```
struct unix_diag_req {

    __u8    sdiag_family;

    __u8    sdiag_protocol;

    __u16   pad;

    __u32   udiag_states;

    __u32   udiag_ino;

    __u32   udiag_show;

    __u32   udiag_cookie[2];
};
```

The fields of this structure are as follows:

sdiag_family

The address family; it should be set to AF_UNIX.

sdiag_protocol

pad

These fields should be set to 0.

udiag_states

This is a bit mask that defines a filter of sockets states. Only those sockets whose states are in this mask will be reported. Ignored when querying for an individual socket. Supported values are:

1 << TCP_ESTABLISHED 1 << TCP_LISTEN

udiag_ino

This is an inode number when querying for an individual socket. Ignored when querying for a list of sockets.

udiag_show

This is a set of flags defining what kind of information to report. Each requested kind of information is reported back as a netlink attribute as described below:

UDIAG_SHOW_NAME

The attribute reported in answer to this request is UNIX_DIAG_NAME. The payload associated with this attribute is the pathname to which the socket was bound (a sequence of bytes up to UNIX_PATH_MAX length).

UDIAG_SHOW_VFS

The attribute reported in answer to this request is UNIX_DIAG_VFS. The payload associated with this attribute is represented in the following structure:

```
struct unix_diag_vfs {

    __u32 udiag_vfs_dev;

    __u32 udiag_vfs_ino;
};

```

The fields of this structure are as follows:

udiag_vfs_dev

The device number of the corresponding on-disk socket inode.

udiag_vfs_ino

The inode number of the corresponding on-disk socket inode.

UDIAG_SHOW_PEER

The attribute reported in answer to this request is UNIX_DIAG_PEER. The payload associated with this attribute is a __u32 value which is the peer's inode number. This attribute is reported for connected sockets only.

UDIAG_SHOW_ICONS

The attribute reported in answer to this request is UNIX_DIAG_ICONS. The payload associated with this attribute is an array of __u32 values which are inode numbers of sockets that has passed the connect(2) call, but hasn't been processed with accept(2) yet. This attribute is reported for listening sockets only.

UDIAG_SHOW_RQLEN

The attribute reported in answer to this request is UNIX_DIAG_RQLEN. The payload associated with this attribute is represented in the following structure:

```
struct unix_diag_rqlen {

    __u32 udiag_rqueue;

    __u32 udiag_wqueue;
};

```

The fields of this structure are as follows:

udiag_rqueue

For listening sockets: the number of pending connections. The length of the array associated with the UNIX_DIAG_ICONS response attribute is equal to this value.

For established sockets: the amount of data in incoming queue.

udiag_wqueue

For listening sockets: the backlog length which equals to the value passed as the second argument to listen(2).

For established sockets: the amount of memory available for sending.

UDIAG_SHOW_MEMINFO

The attribute reported in answer to this request is UNIX_DIAG_MEMINFO. The payload associated with this attribute is an array of __u32 values described below in the subsection "Socket memory information".

The following attributes are reported back without any specific request:

UNIX_DIAG_SHUTDOWN

The payload associated with this attribute is __u8 value which represents bits of shutdown(2) state.

udiag_cookie

This is an array of opaque identifiers that could be used along with udiag_ino to specify an individual socket. It is ignored when querying for a list of sockets, as well as when all its elements are set to -1.

The response to a query for UNIX domain sockets is represented as an array of

```
struct unix_diag_msg {

    __u8    udiag_family;

    __u8    udiag_type;

    __u8    udiag_state;

    __u8    pad;

    __u32   udiag_ino;

    __u32   udiag_cookie[2];
};
```

followed by netlink attributes.

The fields of this structure are as follows:

udiag_family

This field has the same meaning as in struct unix_diag_req.

udiag_type

This is set to one of SOCK_PACKET, SOCK_STREAM, or SOCK_SEQPACKET.

udiag_state

This is set to one of TCP_LISTEN or TCP_ESTABLISHED.

pad

This field is set to 0.

udiag_ino

This is the socket inode number.

udiag_cookie

This is an array of opaque identifiers that could be used in subsequent queries.

### IPv4 and IPv6 sockets
For IPv4 and IPv6 sockets, the request is represented in the following structure:

```
struct inet_diag_req_v2 {

    __u8    sdiag_family;

    __u8    sdiag_protocol;

    __u8    idiag_ext;

    __u8    pad;

    __u32   idiag_states;

    struct inet_diag_sockid id;
};
```

where struct inet_diag_sockid is defined as follows:

```
struct inet_diag_sockid {

    __be16  idiag_sport;

    __be16  idiag_dport;

    __be32  idiag_src[4];

    __be32  idiag_dst[4];

    __u32   idiag_if;

    __u32   idiag_cookie[2];
};
```

The fields of struct inet_diag_req_v2 are as follows:

sdiag_family

This should be set to either AF_INET or AF_INET6 for IPv4 or IPv6 sockets respectively.

sdiag_protocol

This should be set to one of IPPROTO_TCP, IPPROTO_UDP, or IPPROTO_UDPLITE.

idiag_ext

This is a set of flags defining what kind of extended information to report. Each requested kind of information is reported back as a netlink attribute as described below:

INET_DIAG_TOS

The payload associated with this attribute is a __u8 value which is the TOS of the socket.

INET_DIAG_TCLASS

The payload associated with this attribute is a __u8 value which is the TClass of the socket. IPv6 sockets only. For LISTEN and CLOSE sockets, this is followed by INET_DIAG_SKV6ONLY attribute with associated __u8 payload value meaning whether the socket is IPv6-only or not.

INET_DIAG_MEMINFO

The payload associated with this attribute is represented in the following structure:

```
struct inet_diag_meminfo {

    __u32 idiag_rmem;

    __u32 idiag_wmem;

    __u32 idiag_fmem;

    __u32 idiag_tmem;
};

```

The fields of this structure are as follows:

idiag_rmem

The amount of data in the receive queue.

idiag_wmem

The amount of data that is queued by TCP but not yet sent.

idiag_fmem

The amount of memory scheduled for future use (TCP only).

idiag_tmem

The amount of data in send queue.

INET_DIAG_SKMEMINFO

The payload associated with this attribute is an array of __u32 values described below in the subsection "Socket memory information".

INET_DIAG_INFO

The payload associated with this attribute is specific to the address family. For TCP sockets, it is an object of type struct tcp_info.

INET_DIAG_CONG

The payload associated with this attribute is a string that describes the congestion control algorithm used. For TCP sockets only.

pad

This should be set to 0.

idiag_states

This is a bit mask that defines a filter of socket states. Only those sockets whose states are in this mask will be reported. Ignored when querying for an individual socket.

id

This is a socket ID object that is used in dump requests, in queries about individual sockets, and is reported back in each response. Unlike UNIX domain sockets, IPv4 and IPv6 sockets are identified using addresses and ports. All values are in network byte order.

The fields of struct inet_diag_sockid are as follows:

idiag_sport

The source port.

idiag_dport

The destination port.

idiag_src

The source address.

idiag_dst

The destination address.

idiag_if

The interface number the socket is bound to.

idiag_cookie

This is an array of opaque identifiers that could be used along with other fields of this structure to specify an individual socket. It is ignored when querying for a list of sockets, as well as when all its elements are set to -1.

The response to a query for IPv4 or IPv6 sockets is represented as an array of

```
struct inet_diag_msg {

    __u8    idiag_family;

    __u8    idiag_state;

    __u8    idiag_timer;

    __u8    idiag_retrans;

    struct inet_diag_sockid id;

    __u32   idiag_expires;

    __u32   idiag_rqueue;

    __u32   idiag_wqueue;

    __u32   idiag_uid;

    __u32   idiag_inode;
};
```

followed by netlink attributes.

The fields of this structure are as follows:

idiag_family

This is the same field as in struct inet_diag_req_v2.

idiag_state

This denotes socket state as in struct inet_diag_req_v2.

idiag_timer

For TCP sockets, this field describes the type of timer that is currently active for the socket. It is set to one of the following constants:

0

no timer is active

1

a retransmit timer

2

a keep-alive timer

3

a TIME_WAIT timer

4

a zero window probe timer

For non-TCP sockets, this field is set to 0.

idiag_retrans

For idiag_timer values 1, 2, and 4, this field contains the number of retransmits. For other idiag_timer values, this field is set to 0.

idiag_expires

For TCP sockets that have an active timer, this field describes its expiration time in milliseconds. For other sockets, this field is set to 0.

idiag_rqueue

For listening sockets: the number of pending connections.

For other sockets: the amount of data in the incoming queue.

idiag_wqueue

For listening sockets: the backlog length.

For other sockets: the amount of memory available for sending.

idiag_uid

This is the socket owner UID.

idiag_inode

This is the socket inode number.

### Socket memory information
The payload associated with UNIX_DIAG_MEMINFO and INET_DIAG_SKMEMINFO netlink attributes is an array of the following __u32 values:

SK_MEMINFO_RMEM_ALLOC

The amount of data in receive queue.

SK_MEMINFO_RCVBUF

The receive socket buffer as set by SO_RCVBUF.

SK_MEMINFO_WMEM_ALLOC

The amount of data in send queue.

SK_MEMINFO_SNDBUF

The send socket buffer as set by SO_SNDBUF.

SK_MEMINFO_FWD_ALLOC

The amount of memory scheduled for future use (TCP only).

SK_MEMINFO_WMEM_QUEUED

The amount of data queued by TCP, but not yet sent.

SK_MEMINFO_OPTMEM

The amount of memory allocated for the socket's service needs (e.g., socket filter).

SK_MEMINFO_BACKLOG

The amount of packets in the backlog (not yet processed).

## VERSIONS
NETLINK_INET_DIAG was introduced in Linux 2.6.14 and supported AF_INET and AF_INET6 sockets only. In Linux 3.3, it was renamed to NETLINK_SOCK_DIAG and extended to support AF_UNIX sockets.

UNIX_DIAG_MEMINFO and INET_DIAG_SKMEMINFO were introduced in Linux 3.6.

## STANDARDS
Linux.

## EXAMPLES
The following example program prints inode number, peer's inode number, and name of all UNIX domain sockets in the current namespace.

```
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/sock_diag.h>
#include <linux/unix_diag.h>
static int
send_query(int fd)
{

    struct sockaddr_nl nladdr = {

        .nl_family = AF_NETLINK

    };

    struct

    {

        struct nlmsghdr nlh;

        struct unix_diag_req udr;

    } req = {

        .nlh = {

            .nlmsg_len = sizeof(req),

            .nlmsg_type = SOCK_DIAG_BY_FAMILY,

            .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP

        },

        .udr = {

            .sdiag_family = AF_UNIX,

            .udiag_states = -1,

            .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER

        }

    };

    struct iovec iov = {

        .iov_base = &req,

        .iov_len = sizeof(req)

    };

    struct msghdr msg = {

        .msg_name = &nladdr,

        .msg_namelen = sizeof(nladdr),

        .msg_iov = &iov,

        .msg_iovlen = 1

    };

    for (;;) {

        if (sendmsg(fd, &msg, 0) < 0) {

            if (errno == EINTR)

                continue;

            perror("sendmsg");

            return -1;

        }

        return 0;

    }
}
static int
print_diag(const struct unix_diag_msg *diag, unsigned int len)
{

    if (len < NLMSG_LENGTH(sizeof(*diag))) {

        fputs("short response\n", stderr);

        return -1;

    }

    if (diag->udiag_family != AF_UNIX) {

        fprintf(stderr, "unexpected family %u\n", diag->udiag_family);

        return -1;

    }

    unsigned int rta_len = len - NLMSG_LENGTH(sizeof(*diag));

    unsigned int peer = 0;

    size_t path_len = 0;

    char path[sizeof(((struct sockaddr_un *) 0)->sun_path) + 1];

    for (struct rtattr *attr = (struct rtattr *) (diag + 1);

             RTA_OK(attr, rta_len); attr = RTA_NEXT(attr, rta_len)) {

        switch (attr->rta_type) {

        case UNIX_DIAG_NAME:

            if (!path_len) {

                path_len = RTA_PAYLOAD(attr);

                if (path_len > sizeof(path) - 1)

                    path_len = sizeof(path) - 1;

                memcpy(path, RTA_DATA(attr), path_len);

                path[path_len] = '\0';

            }

            break;

        case UNIX_DIAG_PEER:

            if (RTA_PAYLOAD(attr) >= sizeof(peer))

                peer = *(unsigned int *) RTA_DATA(attr);

            break;

        }

    }

    printf("inode=%u", diag->udiag_ino);

    if (peer)

        printf(", peer=%u", peer);

    if (path_len)

        printf(", name=%s%s", *path ? "" : "@",

                *path ? path : path + 1);

    putchar('\n');

    return 0;
}
static int
receive_responses(int fd)
{

    long buf[8192 / sizeof(long)];

    struct sockaddr_nl nladdr;

    struct iovec iov = {

        .iov_base = buf,

        .iov_len = sizeof(buf)

    };

    int flags = 0;

    for (;;) {

        struct msghdr msg = {

            .msg_name = &nladdr,

            .msg_namelen = sizeof(nladdr),

            .msg_iov = &iov,

            .msg_iovlen = 1

        };

        ssize_t ret = recvmsg(fd, &msg, flags);

        if (ret < 0) {

            if (errno == EINTR)

                continue;

            perror("recvmsg");

            return -1;

        }

        if (ret == 0)

            return 0;

        if (nladdr.nl_family != AF_NETLINK) {

            fputs("!AF_NETLINK\n", stderr);

            return -1;

        }

        const struct nlmsghdr *h = (struct nlmsghdr *) buf;

        if (!NLMSG_OK(h, ret)) {

            fputs("!NLMSG_OK\n", stderr);

            return -1;

        }

        for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {

            if (h->nlmsg_type == NLMSG_DONE)

                return 0;

            if (h->nlmsg_type == NLMSG_ERROR) {

                const struct nlmsgerr *err = NLMSG_DATA(h);

                if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*err))) {

                    fputs("NLMSG_ERROR\n", stderr);

                } else {

                    errno = -err->error;

                    perror("NLMSG_ERROR");

                }

                return -1;

            }

            if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY) {

                fprintf(stderr, "unexpected nlmsg_type %u\n",

                        (unsigned) h->nlmsg_type);

                return -1;

            }

            if (print_diag(NLMSG_DATA(h), h->nlmsg_len))

                return -1;

        }

    }
}
int
main(void)
{

    int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);

    if (fd < 0) {

        perror("socket");

        return 1;

    }

    int ret = send_query(fd) || receive_responses(fd);

    close(fd);

    return ret;
}
```

## SEE ALSO
netlink(3), rtnetlink(3), netlink(7), tcp(7)


socket

title: socket(7)

summary: Linux socket interface

text:
# socket(7)

## NAME
socket - Linux socket interface

## SYNOPSIS

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

```
sockfd = socket(int socket_family, int socket_type, int protocol);
```

## DESCRIPTION
This manual page describes the Linux networking socket layer user interface. The BSD compatible sockets are the uniform interface between the user process and the network protocol stacks in the kernel. The protocol modules are grouped into protocol families such as AF_INET, AF_IPX, and AF_PACKET, and socket types such as SOCK_STREAM or SOCK_DGRAM. See socket(2) for more information on families and types.

### Socket-layer functions
These functions are used by the user process to send or receive packets and to do other socket operations. For more information, see their respective manual pages.

socket(2) creates a socket, connect(2) connects a socket to a remote socket address, the bind(2) function binds a socket to a local socket address, listen(2) tells the socket that new connections shall be accepted, and accept(2) is used to get a new socket with a new incoming connection. socketpair(2) returns two connected anonymous sockets (implemented only for a few local families like AF_UNIX)

send(2), sendto(2), and sendmsg(2) send data over a socket, and recv(2), recvfrom(2), recvmsg(2) receive data from a socket. poll(2) and select(2) wait for arriving data or a readiness to send data. In addition, the standard I/O operations like write(2), writev(2), sendfile(2), read(2), and readv(2) can be used to read and write data.

getsockname(2) returns the local socket address and getpeername(2) returns the remote socket address. getsockopt(2) and setsockopt(2) are used to set or get socket layer or protocol options. ioctl(2) can be used to set or read some other options.

close(2) is used to close a socket. shutdown(2) closes parts of a full-duplex socket connection.

Seeking, or calling pread(2) or pwrite(2) with a nonzero position is not supported on sockets.

It is possible to do nonblocking I/O on sockets by setting the O_NONBLOCK flag on a socket file descriptor using fcntl(2). Then all operations that would block will (usually) return with EAGAIN (operation should be retried later); connect(2) will return EINPROGRESS error. The user can then wait for various events via poll(2) or select(2).

I/O events

Event

Poll flag

Occurrence

Read

POLLIN

New data arrived.

Read

POLLIN

A connection setup has been completed (for connection-oriented sockets)

Read

POLLHUP

A disconnection request has been initiated by the other end.

Read

POLLHUP

A connection is broken (only for connection-oriented protocols). When the socket is written SIGPIPE is also sent.

Write

POLLOUT

Socket has enough send buffer space for writing new data.

Read/Write

POLLIN | POLLOUT

An outgoing connect (2) finished.

Read/Write

POLLERR

An asynchronous error occurred.

Read/Write

POLLHUP

The other end has shut down one direction.

Exception

POLLPRI

Urgent data arrived. SIGURG is sent then.

An alternative to poll(2) and select(2) is to let the kernel inform the application about events via a SIGIO signal. For that the O_ASYNC flag must be set on a socket file descriptor via fcntl(2) and a valid signal handler for SIGIO must be installed via sigaction(2). See the Signals discussion below.

### Socket address structures
Each socket domain has its own format for socket addresses, with a domain-specific address structure. Each of these structures begins with an integer "family" field (typed as sa_family_t) that indicates the type of the address structure. This allows the various system calls (e.g., connect(2), bind(2), accept(2), getsockname(2), getpeername(2)), which are generic to all socket domains, to determine the domain of a particular socket address.

To allow any type of socket address to be passed to interfaces in the sockets API, the type struct sockaddr is defined. The purpose of this type is purely to allow casting of domain-specific socket address types to a "generic" type, so as to avoid compiler warnings about type mismatches in calls to the sockets API.

In addition, the sockets API provides the data type struct sockaddr_storage. This type is suitable to accommodate all supported domain-specific socket address structures; it is large enough and is aligned properly. (In particular, it is large enough to hold IPv6 socket addresses.) The structure includes the following field, which can be used to identify the type of socket address actually stored in the structure:

```
    sa_family_t ss_family;
```

The sockaddr_storage structure is useful in programs that must handle socket addresses in a generic way (e.g., programs that must deal with both IPv4 and IPv6 socket addresses).

### Socket options
The socket options listed below can be set by using setsockopt(2) and read with getsockopt(2) with the socket level set to SOL_SOCKET for all sockets. Unless otherwise noted, optval is a pointer to an int.

SO_ACCEPTCONN

Returns a value indicating whether or not this socket has been marked to accept connections with listen(2). The value 0 indicates that this is not a listening socket, the value 1 indicates that this is a listening socket. This socket option is read-only.

SO_ATTACH_FILTER (since Linux 2.2), SO_ATTACH_BPF (since Linux 3.19)

Attach a classic BPF (SO_ATTACH_FILTER) or an extended BPF (SO_ATTACH_BPF) program to the socket for use as a filter of incoming packets. A packet will be dropped if the filter program returns zero. If the filter program returns a nonzero value which is less than the packet's data length, the packet will be truncated to the length returned. If the value returned by the filter is greater than or equal to the packet's data length, the packet is allowed to proceed unmodified.

The argument for SO_ATTACH_FILTER is a sock_fprog structure, defined in <linux/filter.h>:

```
struct sock_fprog {

    unsigned short      len;

    struct sock_filter *filter;
};

```

The argument for SO_ATTACH_BPF is a file descriptor returned by the bpf(2) system call and must refer to a program of type BPF_PROG_TYPE_SOCKET_FILTER.

These options may be set multiple times for a given socket, each time replacing the previous filter program. The classic and extended versions may be called on the same socket, but the previous filter will always be replaced such that a socket never has more than one filter defined.

Both classic and extended BPF are explained in the kernel source file Documentation/networking/filter.txt

SO_ATTACH_REUSEPORT_CBPF, SO_ATTACH_REUSEPORT_EBPF

For use with the SO_REUSEPORT option, these options allow the user to set a classic BPF (SO_ATTACH_REUSEPORT_CBPF) or an extended BPF (SO_ATTACH_REUSEPORT_EBPF) program which defines how packets are assigned to the sockets in the reuseport group (that is, all sockets which have SO_REUSEPORT set and are using the same local address to receive packets).

The BPF program must return an index between 0 and N-1 representing the socket which should receive the packet (where N is the number of sockets in the group). If the BPF program returns an invalid index, socket selection will fall back to the plain SO_REUSEPORT mechanism.

Sockets are numbered in the order in which they are added to the group (that is, the order of bind(2) calls for UDP sockets or the order of listen(2) calls for TCP sockets). New sockets added to a reuseport group will inherit the BPF program. When a socket is removed from a reuseport group (via close(2)), the last socket in the group will be moved into the closed socket's position.

These options may be set repeatedly at any time on any socket in the group to replace the current BPF program used by all sockets in the group.

SO_ATTACH_REUSEPORT_CBPF takes the same argument type as SO_ATTACH_FILTER and SO_ATTACH_REUSEPORT_EBPF takes the same argument type as SO_ATTACH_BPF.

UDP support for this feature is available since Linux 4.5; TCP support is available since Linux 4.6.

SO_BINDTODEVICE

Bind this socket to a particular device like “eth0”, as specified in the passed interface name. If the name is an empty string or the option length is zero, the socket device binding is removed. The passed option is a variable-length null-terminated interface name string with the maximum size of IFNAMSIZ. If a socket is bound to an interface, only packets received from that particular interface are processed by the socket. Note that this works only for some socket types, particularly AF_INET sockets. It is not supported for packet sockets (use normal bind(2) there).

Before Linux 3.8, this socket option could be set, but could not retrieved with getsockopt(2). Since Linux 3.8, it is readable. The optlen argument should contain the buffer size available to receive the device name and is recommended to be IFNAMSIZ bytes. The real device name length is reported back in the optlen argument.

SO_BROADCAST

Set or get the broadcast flag. When enabled, datagram sockets are allowed to send packets to a broadcast address. This option has no effect on stream-oriented sockets.

SO_BSDCOMPAT

Enable BSD bug-to-bug compatibility. This is used by the UDP protocol module in Linux 2.0 and 2.2. If enabled, ICMP errors received for a UDP socket will not be passed to the user program. In later kernel versions, support for this option has been phased out: Linux 2.4 silently ignores it, and Linux 2.6 generates a kernel warning (printk()) if a program uses this option. Linux 2.0 also enabled BSD bug-to-bug compatibility options (random header changing, skipping of the broadcast flag) for raw sockets with this option, but that was removed in Linux 2.2.

SO_DEBUG

Enable socket debugging. Allowed only for processes with the CAP_NET_ADMIN capability or an effective user ID of 0.

SO_DETACH_FILTER (since Linux 2.2), SO_DETACH_BPF (since Linux 3.19)

These two options, which are synonyms, may be used to remove the classic or extended BPF program attached to a socket with either SO_ATTACH_FILTER or SO_ATTACH_BPF. The option value is ignored.

SO_DOMAIN (since Linux 2.6.32)

Retrieves the socket domain as an integer, returning a value such as AF_INET6. See socket(2) for details. This socket option is read-only.

SO_ERROR

Get and clear the pending socket error. This socket option is read-only. Expects an integer.

SO_DONTROUTE

Don't send via a gateway, send only to directly connected hosts. The same effect can be achieved by setting the MSG_DONTROUTE flag on a socket send(2) operation. Expects an integer boolean flag.

SO_INCOMING_CPU (gettable since Linux 3.19, settable since Linux 4.4)

Sets or gets the CPU affinity of a socket. Expects an integer flag.

```
int cpu = 1;
setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu,

           sizeof(cpu));

```

Because all of the packets for a single stream (i.e., all packets for the same 4-tuple) arrive on the single RX queue that is associated with a particular CPU, the typical use case is to employ one listening process per RX queue, with the incoming flow being handled by a listener on the same CPU that is handling the RX queue. This provides optimal NUMA behavior and keeps CPU caches hot.

SO_INCOMING_NAPI_ID (gettable since Linux 4.12)

Returns a system-level unique ID called NAPI ID that is associated with a RX queue on which the last packet associated with that socket is received.

This can be used by an application to split the incoming flows among worker threads based on the RX queue on which the packets associated with the flows are received. It allows each worker thread to be associated with a NIC HW receive queue and service all the connection requests received on that RX queue. This mapping between an app thread and a HW NIC queue streamlines the flow of data from the NIC to the application.

SO_KEEPALIVE

Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag.

SO_LINGER

Sets or gets the SO_LINGER option. The argument is a linger structure.

```
struct linger {

    int l_onoff;    /* linger active */

    int l_linger;   /* how many seconds to linger for */
};

```

When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of exit(2), it always lingers in the background.

SO_LOCK_FILTER

When set, this option will prevent changing the filters associated with the socket. These filters include any set using the socket options SO_ATTACH_FILTER, SO_ATTACH_BPF, SO_ATTACH_REUSEPORT_CBPF, and SO_ATTACH_REUSEPORT_EBPF.

The typical use case is for a privileged process to set up a raw socket (an operation that requires the CAP_NET_RAW capability), apply a restrictive filter, set the SO_LOCK_FILTER option, and then either drop its privileges or pass the socket file descriptor to an unprivileged process via a UNIX domain socket.

Once the SO_LOCK_FILTER option has been enabled, attempts to change or remove the filter attached to a socket, or to disable the SO_LOCK_FILTER option will fail with the error EPERM.

SO_MARK (since Linux 2.6.25)

Set the mark for each packet sent through this socket (similar to the netfilter MARK target but socket-based). Changing the mark can be used for mark-based routing without netfilter or for packet filtering. Setting this option requires the CAP_NET_ADMIN capability.

SO_OOBINLINE

If this option is enabled, out-of-band data is directly placed into the receive data stream. Otherwise, out-of-band data is passed only when the MSG_OOB flag is set during receiving.

SO_PASSCRED

Enable or disable the receiving of the SCM_CREDENTIALS control message. For more information, see unix(7).

SO_PASSSEC

Enable or disable the receiving of the SCM_SECURITY control message. For more information, see unix(7).

SO_PEEK_OFF (since Linux 3.4)

This option, which is currently supported only for unix(7) sockets, sets the value of the "peek offset" for the recv(2) system call when used with MSG_PEEK flag.

When this option is set to a negative value (it is set to -1 for all new sockets), traditional behavior is provided: recv(2) with the MSG_PEEK flag will peek data from the front of the queue.

When the option is set to a value greater than or equal to zero, then the next peek at data queued in the socket will occur at the byte offset specified by the option value. At the same time, the "peek offset" will be incremented by the number of bytes that were peeked from the queue, so that a subsequent peek will return the next data in the queue.

If data is removed from the front of the queue via a call to recv(2) (or similar) without the MSG_PEEK flag, the "peek offset" will be decreased by the number of bytes removed. In other words, receiving data without the MSG_PEEK flag will cause the "peek offset" to be adjusted to maintain the correct relative position in the queued data, so that a subsequent peek will retrieve the data that would have been retrieved had the data not been removed.

For datagram sockets, if the "peek offset" points to the middle of a packet, the data returned will be marked with the MSG_TRUNC flag.

The following example serves to illustrate the use of SO_PEEK_OFF. Suppose a stream socket has the following queued input data:

```
aabbccddeeff

```

The following sequence of recv(2) calls would have the effect noted in the comments:

```
int ov = 4;                  // Set peek offset to 4
setsockopt(fd, SOL_SOCKET, SO_PEEK_OFF, &ov, sizeof(ov));
recv(fd, buf, 2, MSG_PEEK);  // Peeks "cc"; offset set to 6
recv(fd, buf, 2, MSG_PEEK);  // Peeks "dd"; offset set to 8
recv(fd, buf, 2, 0);         // Reads "aa"; offset set to 6
recv(fd, buf, 2, MSG_PEEK);  // Peeks "ee"; offset set to 8

```

SO_PEERCRED

Return the credentials of the peer process connected to this socket. For further details, see unix(7).

SO_PEERSEC (since Linux 2.6.2)

Return the security context of the peer socket connected to this socket. For further details, see unix(7) and ip(7).

SO_PRIORITY

Set the protocol-defined priority for all packets to be sent on this socket. Linux uses this value to order the networking queues: packets with a higher priority may be processed first depending on the selected device queueing discipline. Setting a priority outside the range 0 to 6 requires the CAP_NET_ADMIN capability.

SO_PROTOCOL (since Linux 2.6.32)

Retrieves the socket protocol as an integer, returning a value such as IPPROTO_SCTP. See socket(2) for details. This socket option is read-only.

SO_RCVBUF

Sets or gets the maximum socket receive buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(2), and this doubled value is returned by getsockopt(2). The default value is set by the /proc/sys/net/core/rmem_default file, and the maximum allowed value is set by the /proc/sys/net/core/rmem_max file. The minimum (doubled) value for this option is 256.

SO_RCVBUFFORCE (since Linux 2.6.14)

Using this socket option, a privileged (CAP_NET_ADMIN) process can perform the same task as SO_RCVBUF, but the rmem_max limit can be overridden.

SO_RCVLOWAT and SO_SNDLOWAT

Specify the minimum number of bytes in the buffer until the socket layer will pass the data to the protocol (SO_SNDLOWAT) or the user on receiving (SO_RCVLOWAT). These two values are initialized to 1. SO_SNDLOWAT is not changeable on Linux (setsockopt(2) fails with the error ENOPROTOOPT). SO_RCVLOWAT is changeable only since Linux 2.4.

Before Linux 2.6.28 select(2), poll(2), and epoll(7) did not respect the SO_RCVLOWAT setting on Linux, and indicated a socket as readable when even a single byte of data was available. A subsequent read from the socket would then block until SO_RCVLOWAT bytes are available. Since Linux 2.6.28, select(2), poll(2), and epoll(7) indicate a socket as readable only if at least SO_RCVLOWAT bytes are available.

SO_RCVTIMEO and SO_SNDTIMEO

Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached, then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default), then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., accept(2), connect(2), read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), and so on.

SO_REUSEADDR

Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. When the listening socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address. Argument is an integer boolean flag.

SO_REUSEPORT (since Linux 3.9)

Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.

For TCP sockets, this option allows accept(2) load distribution in a multi-threaded server to be improved by using a distinct listener socket for each thread. This provides improved load distribution as compared to traditional techniques such using a single accept(2)ing thread that distributes connections, or having multiple threads that compete to accept(2) from the same socket.

For UDP sockets, the use of this option can provide better distribution of incoming datagrams to multiple processes (or threads) as compared to the traditional technique of having multiple processes compete to receive datagrams on the same socket.

SO_RXQ_OVFL (since Linux 2.6.33)

Indicates that an unsigned 32-bit value ancillary message (cmsg) should be attached to received skbs indicating the number of packets dropped by the socket since its creation.

SO_SELECT_ERR_QUEUE (since Linux 3.10)

When this option is set on a socket, an error condition on a socket causes notification not only via the exceptfds set of select(2). Similarly, poll(2) also returns a POLLPRI whenever an POLLERR event is returned.

Background: this option was added when waking up on an error condition occurred only via the readfds and writefds sets of select(2). The option was added to allow monitoring for error conditions via the exceptfds argument without simultaneously having to receive notifications (via readfds) for regular data that can be read from the socket. After changes in Linux 4.16, the use of this flag to achieve the desired notifications is no longer necessary. This option is nevertheless retained for backwards compatibility.

SO_SNDBUF

Sets or gets the maximum socket send buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(2), and this doubled value is returned by getsockopt(2). The default value is set by the /proc/sys/net/core/wmem_default file and the maximum allowed value is set by the /proc/sys/net/core/wmem_max file. The minimum (doubled) value for this option is 2048.

SO_SNDBUFFORCE (since Linux 2.6.14)

Using this socket option, a privileged (CAP_NET_ADMIN) process can perform the same task as SO_SNDBUF, but the wmem_max limit can be overridden.

SO_TIMESTAMP

Enable or disable the receiving of the SO_TIMESTAMP control message. The timestamp control message is sent with level SOL_SOCKET and a cmsg_type of SCM_TIMESTAMP. The cmsg_data field is a struct timeval indicating the reception time of the last packet passed to the user in this call. See cmsg(3) for details on control messages.

SO_TIMESTAMPNS (since Linux 2.6.22)

Enable or disable the receiving of the SO_TIMESTAMPNS control message. The timestamp control message is sent with level SOL_SOCKET and a cmsg_type of SCM_TIMESTAMPNS. The cmsg_data field is a struct timespec indicating the reception time of the last packet passed to the user in this call. The clock used for the timestamp is CLOCK_REALTIME. See cmsg(3) for details on control messages.

A socket cannot mix SO_TIMESTAMP and SO_TIMESTAMPNS: the two modes are mutually exclusive.

SO_TYPE

Gets the socket type as an integer (e.g., SOCK_STREAM). This socket option is read-only.

SO_BUSY_POLL (since Linux 3.11)

Sets the approximate time in microseconds to busy poll on a blocking receive when there is no data. Increasing this value requires CAP_NET_ADMIN. The default for this option is controlled by the /proc/sys/net/core/busy_read file.

The value in the /proc/sys/net/core/busy_poll file determines how long select(2) and poll(2) will busy poll when they operate on sockets with SO_BUSY_POLL set and no events to report are found.

In both cases, busy polling will only be done when the socket last received data from a network device that supports this option.

While busy polling may improve latency of some applications, care must be taken when using it since this will increase both CPU utilization and power usage.

### Signals
When writing onto a connection-oriented socket that has been shut down (by the local or the remote end) SIGPIPE is sent to the writing process and EPIPE is returned. The signal is not sent when the write call specified the MSG_NOSIGNAL flag.

When requested with the FIOSETOWN fcntl(2) or SIOCSPGRP ioctl(2), SIGIO is sent when an I/O event occurs. It is possible to use poll(2) or select(2) in the signal handler to find out which socket the event occurred on. An alternative (in Linux 2.2) is to set a real-time signal using the F_SETSIG fcntl(2); the handler of the real time signal will be called with the file descriptor in the si_fd field of its siginfo_t. See fcntl(2) for more information.

Under some circumstances (e.g., multiple processes accessing a single socket), the condition that caused the SIGIO may have already disappeared when the process reacts to the signal. If this happens, the process should wait again because Linux will resend the signal later.

### /proc interfaces
The core socket networking parameters can be accessed via files in the directory /proc/sys/net/core/.

rmem_default

contains the default setting in bytes of the socket receive buffer.

rmem_max

contains the maximum socket receive buffer size in bytes which a user may set by using the SO_RCVBUF socket option.

wmem_default

contains the default setting in bytes of the socket send buffer.

wmem_max

contains the maximum socket send buffer size in bytes which a user may set by using the SO_SNDBUF socket option.

message_cost and message_burst

configure the token bucket filter used to load limit warning messages caused by external network events.

netdev_max_backlog

Maximum number of packets in the global input queue.

optmem_max

Maximum length of ancillary data and user control data like the iovecs per socket.

### Ioctls
These operations can be accessed using ioctl(2):

```
error = ioctl(ip_socket, ioctl_type, &value_result);
```

SIOCGSTAMP

Return a struct timeval with the receive timestamp of the last packet passed to the user. This is useful for accurate round trip time measurements. See setitimer(2) for a description of struct timeval. This ioctl should be used only if the socket options SO_TIMESTAMP and SO_TIMESTAMPNS are not set on the socket. Otherwise, it returns the timestamp of the last packet that was received while SO_TIMESTAMP and SO_TIMESTAMPNS were not set, or it fails if no such packet has been received, (i.e., ioctl(2) returns -1 with errno set to ENOENT).

SIOCSPGRP

Set the process or process group that is to receive SIGIO or SIGURG signals when I/O becomes possible or urgent data is available. The argument is a pointer to a pid_t. For further details, see the description of F_SETOWN in fcntl(2).

FIOASYNC

Change the O_ASYNC flag to enable or disable asynchronous I/O mode of the socket. Asynchronous I/O mode means that the SIGIO signal or the signal set with F_SETSIG is raised when a new I/O event occurs.

Argument is an integer boolean flag. (This operation is synonymous with the use of fcntl(2) to set the O_ASYNC flag.)

SIOCGPGRP

Get the current process or process group that receives SIGIO or SIGURG signals, or 0 when none is set.

Valid fcntl(2) operations:

FIOGETOWN

The same as the SIOCGPGRP ioctl(2).

FIOSETOWN

The same as the SIOCSPGRP ioctl(2).

## VERSIONS
SO_BINDTODEVICE was introduced in Linux 2.0.30. SO_PASSCRED is new in Linux 2.2. The /proc interfaces were introduced in Linux 2.2. SO_RCVTIMEO and SO_SNDTIMEO are supported since Linux 2.3.41. Earlier, timeouts were fixed to a protocol-specific setting, and could not be read or written.

## NOTES
Linux assumes that half of the send/receive buffer is used for internal kernel structures; thus the values in the corresponding /proc files are twice what can be observed on the wire.

Linux will allow port reuse only with the SO_REUSEADDR option when this option was set both in the previous program that performed a bind(2) to the port and in the program that wants to reuse the port. This differs from some implementations (e.g., FreeBSD) where only the later program needs to set the SO_REUSEADDR option. Typically this difference is invisible, since, for example, a server program is designed to always set this option.

## SEE ALSO
wireshark(1), bpf(2), connect(2), getsockopt(2), setsockopt(2), socket(2), pcap(3), address_families(7), capabilities(7), ddp(7), ip(7), ipv6(7), packet(7), tcp(7), udp(7), unix(7), tcpdump(8)


spufs

title: spufs(7)

summary: SPU filesystem

text:
# spufs(7)

## NAME
spufs - SPU filesystem

## DESCRIPTION
The SPU filesystem is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to access Synergistic Processor Units (SPUs).

The filesystem provides a name space similar to POSIX shared memory or message queues. Users that have write permissions on the filesystem can use spu_create(2) to establish SPU contexts under the spufs root directory.

Every SPU context is represented by a directory containing a predefined set of files. These files can be used for manipulating the state of the logical SPU. Users can change permissions on the files, but can't add or remove files.

### Mount options
uid=<uid>

Set the user owning the mount point; the default is 0 (root).

gid=<gid>

Set the group owning the mount point; the default is 0 (root).

mode=<mode>

Set the mode of the top-level directory in spufs, as an octal mode string. The default is 0775.

### Files
The files in spufs mostly follow the standard behavior for regular system calls like read(2) or write(2), but often support only a subset of the operations supported on regular filesystems. This list details the supported operations and the deviations from the standard behavior described in the respective man pages.

All files that support the read(2) operation also support readv(2) and all files that support the write(2) operation also support writev(2). All files support the access(2) and stat(2) family of operations, but for the latter call, the only fields of the returned stat structure that contain reliable information are st_mode, st_nlink, st_uid, and st_gid.

All files support the chmod(2)/fchmod(2) and chown(2)/fchown(2) operations, but will not be able to grant permissions that contradict the possible operations (e.g., read access on the wbox file).

The current set of files is:

/capabilities

Contains a comma-delimited string representing the capabilities of this SPU context. Possible capabilities are:

sched

This context may be scheduled.

step

This context can be run in single-step mode, for debugging.

New capabilities flags may be added in the future.

/mem

the contents of the local storage memory of the SPU. This can be accessed like a regular shared memory file and contains both code and data in the address space of the SPU. The possible operations on an open mem file are:

read(2), pread(2), write(2), pwrite(2), lseek(2)

These operate as usual, with the exception that lseek(2), write(2), and pwrite(2) are not supported beyond the end of the file. The file size is the size of the local storage of the SPU, which is normally 256 kilobytes.

mmap(2)

Mapping mem into the process address space provides access to the SPU local storage within the process address space. Only MAP_SHARED mappings are allowed.

/regs

Contains the saved general-purpose registers of the SPU context. This file contains the 128-bit values of each register, from register 0 to register 127, in order. This allows the general-purpose registers to be inspected for debugging.

Reading to or writing from this file requires that the context is scheduled out, so use of this file is not recommended in normal program operation.

The regs file is not present on contexts that have been created with the SPU_CREATE_NOSCHED flag.

/mbox

The first SPU-to-CPU communication mailbox. This file is read-only and can be read in units of 4 bytes. The file can be used only in nonblocking mode - even poll(2) cannot be used to block on this file. The only possible operation on an open mbox file is:

read(2)

If count is smaller than four, read(2) returns -1 and sets errno to EINVAL. If there is no data available in the mailbox (i.e., the SPU has not sent a mailbox message), the return value is set to -1 and errno is set to EAGAIN. When data has been read successfully, four bytes are placed in the data buffer and the value four is returned.

/ibox

The second SPU-to-CPU communication mailbox. This file is similar to the first mailbox file, but can be read in blocking I/O mode, thus calling read(2) on an open ibox file will block until the SPU has written data to its interrupt mailbox channel (unless the file has been opened with O_NONBLOCK, see below). Also, poll(2) and similar system calls can be used to monitor for the presence of mailbox data.

The possible operations on an open ibox file are:

read(2)

If count is smaller than four, read(2) returns -1 and sets errno to EINVAL. If there is no data available in the mailbox and the file descriptor has been opened with O_NONBLOCK, the return value is set to -1 and errno is set to EAGAIN.

If there is no data available in the mailbox and the file descriptor has been opened without O_NONBLOCK, the call will block until the SPU writes to its interrupt mailbox channel. When data has been read successfully, four bytes are placed in the data buffer and the value four is returned.

poll(2)

Poll on the ibox file returns (POLLIN | POLLRDNORM) whenever data is available for reading.

/wbox

The CPU-to-SPU communication mailbox. It is write-only and can be written in units of four bytes. If the mailbox is full, write(2) will block, and poll(2) can be used to block until the mailbox is available for writing again. The possible operations on an open wbox file are:

write(2)

If count is smaller than four, write(2) returns -1 and sets errno to EINVAL. If there is no space available in the mailbox and the file descriptor has been opened with O_NONBLOCK, the return value is set to -1 and errno is set to EAGAIN.

If there is no space available in the mailbox and the file descriptor has been opened without O_NONBLOCK, the call will block until the SPU reads from its PPE (PowerPC Processing Element) mailbox channel. When data has been written successfully, the system call returns four as its function result.

poll(2)

A poll on the wbox file returns (POLLOUT | POLLWRNORM) whenever space is available for writing.

/mbox_stat, /ibox_stat, /wbox_stat

These are read-only files that contain the length of the current queue of each mailbox—that is, how many words can be read from mbox or ibox or how many words can be written to wbox without blocking. The files can be read only in four-byte units and return a big-endian binary integer number. The only possible operation on an open *box_stat file is:

read(2)

If count is smaller than four, read(2) returns -1 and sets errno to EINVAL. Otherwise, a four-byte value is placed in the data buffer. This value is the number of elements that can be read from (for mbox_stat and ibox_stat) or written to (for wbox_stat) the respective mailbox without blocking or returning an EAGAIN error.

/npc, /decr, /decr_status, /spu_tag_mask, /event_mask, /event_status, /srr0, /lslr

Internal registers of the SPU. These files contain an ASCII string representing the hex value of the specified register. Reads and writes on these files (except for npc, see below) require that the SPU context be scheduled out, so frequent access to these files is not recommended for normal program operation.

The contents of these files are:

npc

Next Program Counter - valid only when the SPU is in a stopped state.

decr

SPU Decrementer

decr_status

Decrementer Status

spu_tag_mask

MFC tag mask for SPU DMA

event_mask

Event mask for SPU interrupts

event_status

Number of SPU events pending (read-only)

srr0

Interrupt Return address register

lslr

Local Store Limit Register

The possible operations on these files are:

read(2)

Reads the current register value. If the register value is larger than the buffer passed to the read(2) system call, subsequent reads will continue reading from the same buffer, until the end of the buffer is reached.

When a complete string has been read, all subsequent read operations will return zero bytes and a new file descriptor needs to be opened to read a new value.

write(2)

A write(2) operation on the file sets the register to the value given in the string. The string is parsed from the beginning until the first nonnumeric character or the end of the buffer. Subsequent writes to the same file descriptor overwrite the previous setting.

Except for the npc file, these files are not present on contexts that have been created with the SPU_CREATE_NOSCHED flag.

/fpcr

This file provides access to the Floating Point Status and Control Register (fcpr) as a binary, four-byte file. The operations on the fpcr file are:

read(2)

If count is smaller than four, read(2) returns -1 and sets errno to EINVAL. Otherwise, a four-byte value is placed in the data buffer; this is the current value of the fpcr register.

write(2)

If count is smaller than four, write(2) returns -1 and sets errno to EINVAL. Otherwise, a four-byte value is copied from the data buffer, updating the value of the fpcr register.

/signal1, /signal2

The files provide access to the two signal notification channels of an SPU. These are read-write files that operate on four-byte words. Writing to one of these files triggers an interrupt on the SPU. The value written to the signal files can be read from the SPU through a channel read or from host user space through the file. After the value has been read by the SPU, it is reset to zero. The possible operations on an open signal1 or signal2 file are:

read(2)

If count is smaller than four, read(2) returns -1 and sets errno to EINVAL. Otherwise, a four-byte value is placed in the data buffer; this is the current value of the specified signal notification register.

write(2)

If count is smaller than four, write(2) returns -1 and sets errno to EINVAL. Otherwise, a four-byte value is copied from the data buffer, updating the value of the specified signal notification register. The signal notification register will either be replaced with the input data or will be updated to the bitwise OR operation of the old value and the input data, depending on the contents of the signal1_type or signal2_type files respectively.

/signal1_type, /signal2_type

These two files change the behavior of the signal1 and signal2 notification files. They contain a numeric ASCII string which is read as either "1" or "0". In mode 0 (overwrite), the hardware replaces the contents of the signal channel with the data that is written to it. In mode 1 (logical OR), the hardware accumulates the bits that are subsequently written to it. The possible operations on an open signal1_type or signal2_type file are:

read(2)

When the count supplied to the read(2) call is shorter than the required length for the digit (plus a newline character), subsequent reads from the same file descriptor will complete the string. When a complete string has been read, all subsequent read operations will return zero bytes and a new file descriptor needs to be opened to read the value again.

write(2)

A write(2) operation on the file sets the register to the value given in the string. The string is parsed from the beginning until the first nonnumeric character or the end of the buffer. Subsequent writes to the same file descriptor overwrite the previous setting.

/mbox_info, /ibox_info, /wbox_info, /dma_into, /proxydma_info

Read-only files that contain the saved state of the SPU mailboxes and DMA queues. This allows the SPU status to be inspected, mainly for debugging. The mbox_info and ibox_info files each contain the four-byte mailbox message that has been written by the SPU. If no message has been written to these mailboxes, then contents of these files is undefined. The mbox_stat, ibox_stat, and wbox_stat files contain the available message count.

The wbox_info file contains an array of four-byte mailbox messages, which have been sent to the SPU. With current CBEA machines, the array is four items in length, so up to 4 * 4 = 16 bytes can be read from this file. If any mailbox queue entry is empty, then the bytes read at the corresponding location are undefined.

The dma_info file contains the contents of the SPU MFC DMA queue, represented as the following structure:

```
struct spu_dma_info {

    uint64_t         dma_info_type;

    uint64_t         dma_info_mask;

    uint64_t         dma_info_status;

    uint64_t         dma_info_stall_and_notify;

    uint64_t         dma_info_atomic_command_status;

    struct mfc_cq_sr dma_info_command_data[16];
};

```

The last member of this data structure is the actual DMA queue, containing 16 entries. The mfc_cq_sr structure is defined as:

```
struct mfc_cq_sr {

    uint64_t mfc_cq_data0_RW;

    uint64_t mfc_cq_data1_RW;

    uint64_t mfc_cq_data2_RW;

    uint64_t mfc_cq_data3_RW;
};

```

The proxydma_info file contains similar information, but describes the proxy DMA queue (i.e., DMAs initiated by entities outside the SPU) instead. The file is in the following format:

```
struct spu_proxydma_info {

    uint64_t         proxydma_info_type;

    uint64_t         proxydma_info_mask;

    uint64_t         proxydma_info_status;

    struct mfc_cq_sr proxydma_info_command_data[8];
};

```

Accessing these files requires that the SPU context is scheduled out - frequent use can be inefficient. These files should not be used for normal program operation.

These files are not present on contexts that have been created with the SPU_CREATE_NOSCHED flag.

/cntl

This file provides access to the SPU Run Control and SPU status registers, as an ASCII string. The following operations are supported:

read(2)

Reads from the cntl file will return an ASCII string with the hex value of the SPU Status register.

write(2)

Writes to the cntl file will set the context's SPU Run Control register.

/mfc

Provides access to the Memory Flow Controller of the SPU. Reading from the file returns the contents of the SPU's MFC Tag Status register, and writing to the file initiates a DMA from the MFC. The following operations are supported:

write(2)

Writes to this file need to be in the format of a MFC DMA command, defined as follows:

```
struct mfc_dma_command {

    int32_t  pad;    /* reserved */

    uint32_t lsa;    /* local storage address */

    uint64_t ea;     /* effective address */

    uint16_t size;   /* transfer size */

    uint16_t tag;    /* command tag */

    uint16_t class;  /* class ID */

    uint16_t cmd;    /* command opcode */
};

```

Writes are required to be exactly sizeof(struct mfc_dma_command) bytes in size. The command will be sent to the SPU's MFC proxy queue, and the tag stored in the kernel (see below).

read(2)

Reads the contents of the tag status register. If the file is opened in blocking mode (i.e., without O_NONBLOCK), then the read will block until a DMA tag (as performed by a previous write) is complete. In nonblocking mode, the MFC tag status register will be returned without waiting.

poll(2)

Calling poll(2) on the mfc file will block until a new DMA can be started (by checking for POLLOUT) or until a previously started DMA (by checking for POLLIN) has been completed.

/mss Provides access to the MFC MultiSource Synchronization (MSS) facility. By mmap(2)-ing this file, processes can access the MSS area of the SPU.

The following operations are supported:

mmap(2)

Mapping mss into the process address space gives access to the SPU MSS area within the process address space. Only MAP_SHARED mappings are allowed.

/psmap

Provides access to the whole problem-state mapping of the SPU. Applications can use this area to interface to the SPU, rather than writing to individual register files in spufs.

The following operations are supported:

mmap(2)

Mapping psmap gives a process a direct map of the SPU problem state area. Only MAP_SHARED mappings are supported.

/phys-id

Read-only file containing the physical SPU number that the SPU context is running on. When the context is not running, this file contains the string "-1".

The physical SPU number is given by an ASCII hex string.

/object-id

Allows applications to store (or retrieve) a single 64-bit ID into the context. This ID is later used by profiling tools to uniquely identify the context.

write(2)

By writing an ASCII hex value into this file, applications can set the object ID of the SPU context. Any previous value of the object ID is overwritten.

read(2)

Reading this file gives an ASCII hex string representing the object ID for this SPU context.

## EXAMPLES
To automatically mount(8) the SPU filesystem when booting, at the location /spu chosen by the user, put this line into the fstab(5) configuration file:

```
none /spu spufs gid=spu 0 0
```

## SEE ALSO
close(2), spu_create(2), spu_run(2), capabilities(7)

The Cell Broadband Engine Architecture (CBEA) specification