signal-safety

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:

1.

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

2.

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 cancellation points and nest over regions of deferred cancellation may trigger cancellation whose behavior is as if asynchronous cancellation 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)


package: man-pages

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.

## CONFORMING TO
The NETLINK_SOCK_DIAG API is Linux-specific.

## 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 a 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., 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
/etc/fstab entry

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


standards

title: standards(7)

summary: C and UNIX Standards

text:
# standards(7)

## NAME
standards - C and UNIX Standards

## DESCRIPTION
The CONFORMING TO section that appears in many manual pages identifies various standards to which the documented interface conforms. The following list briefly describes these standards.

V7

Version 7 (also known as Seventh Edition) UNIX, released by AT&T/Bell Labs in 1979. After this point, UNIX systems diverged into two main dialects: BSD and System V.

4.2BSD

This is an implementation standard defined by the 4.2 release of the Berkeley Software Distribution, released by the University of California at Berkeley. This was the first Berkeley release that contained a TCP/IP stack and the sockets API. 4.2BSD was released in 1983.

Earlier major BSD releases included 3BSD (1980), 4BSD (1980), and 4.1BSD (1981).

4.3BSD

The successor to 4.2BSD, released in 1986.

4.4BSD

The successor to 4.3BSD, released in 1993. This was the last major Berkeley release.

System V

This is an implementation standard defined by AT&T's milestone 1983 release of its commercial System V (five) release. The previous major AT&T release was System III, released in 1981.

System V release 2 (SVr2)

This was the next System V release, made in 1985. The SVr2 was formally described in the System V Interface Definition version 1 (SVID 1) published in 1985.

System V release 3 (SVr3)

This was the successor to SVr2, released in 1986. This release was formally described in the System V Interface Definition version 2 (SVID 2).

System V release 4 (SVr4)

This was the successor to SVr3, released in 1989. This version of System V is described in the "Programmer's Reference Manual: Operating System API (Intel processors)" (Prentice-Hall 1992, ISBN 0-13-951294-2) This release was formally described in the System V Interface Definition version 3 (SVID 3), and is considered the definitive System V release.

SVID 4

System V Interface Definition version 4, issued in 1995. Available online at http://www.sco.com/developers/devspecs/.

C89

This was the first C language standard, ratified by ANSI (American National Standards Institute) in 1989 (X3.159-1989). Sometimes this is known as ANSI C, but since C99 is also an ANSI standard, this term is ambiguous. This standard was also ratified by ISO (International Standards Organization) in 1990 (ISO/IEC 9899:1990), and is thus occasionally referred to as ISO C90.

C99

This revision of the C language standard was ratified by ISO in 1999 (ISO/IEC 9899:1999). Available online at http://www.open-std.org/jtc1/sc22/wg14/www/standards.

C11

This revision of the C language standard was ratified by ISO in 2011 (ISO/IEC 9899:2011).

LFS The Large File Summit specification, completed in 1996. This specification defined mechanisms that allowed 32-bit systems to support the use of large files (i.e., 64-bit file offsets). See https://www.opengroup.org/platform/lfs.html.

POSIX.1-1988

This was the first POSIX standard, ratified by IEEE as IEEE Std 1003.1-1988, and subsequently adopted (with minor revisions) as an ISO standard in 1990. The term "POSIX" was coined by Richard Stallman.

POSIX.1-1990

"Portable Operating System Interface for Computing Environments". IEEE 1003.1-1990 part 1, ratified by ISO in 1990 (ISO/IEC 9945-1:1990).

POSIX.2

IEEE Std 1003.2-1992, describing commands and utilities, ratified by ISO in 1993 (ISO/IEC 9945-2:1993).

POSIX.1b (formerly known as POSIX.4)

IEEE Std 1003.1b-1993, describing real-time facilities for portable operating systems, ratified by ISO in 1996 (ISO/IEC 9945-1:1996).

POSIX.1c (formerly known as POSIX.4a)

IEEE Std 1003.1c-1995, which describes the POSIX threads interfaces.

POSIX.1d

IEEE Std 1003.1c-1999, which describes additional real-time extensions.

POSIX.1g

IEEE Std 1003.1g-2000, which describes networking APIs (including sockets).

POSIX.1j

IEEE Std 1003.1j-2000, which describes advanced real-time extensions.

POSIX.1-1996

A 1996 revision of POSIX.1 which incorporated POSIX.1b and POSIX.1c.

XPG3

Released in 1989, this was the first release of the X/Open Portability Guide to be based on a POSIX standard (POSIX.1-1988). This multivolume guide was developed by the X/Open Group, a multivendor consortium.

XPG4

A revision of the X/Open Portability Guide, released in 1992. This revision incorporated POSIX.2.

XPG4v2

A 1994 revision of XPG4. This is also referred to as Spec 1170, where 1170 referred to the number of interfaces defined by this standard.

SUS (SUSv1)

Single UNIX Specification. This was a repackaging of XPG4v2 and other X/Open standards (X/Open Curses Issue 4 version 2, X/Open Networking Service (XNS) Issue 4). Systems conforming to this standard can be branded UNIX 95.

SUSv2

Single UNIX Specification version 2. Sometimes also referred to (incorrectly) as XPG5. This standard appeared in 1997. Systems conforming to this standard can be branded UNIX 98. See also http://www.unix.org/version2/.)

POSIX.1-2001, SUSv3

This was a 2001 revision and consolidation of the POSIX.1, POSIX.2, and SUS standards into a single document, conducted under the auspices of the Austin Group http://www.opengroup.org/austin/. The standard is available online at http://www.unix.org/version3/.

The standard defines two levels of conformance: POSIX conformance, which is a baseline set of interfaces required of a conforming system; and XSI Conformance, which additionally mandates a set of interfaces (the "XSI extension") which are only optional for POSIX conformance. XSI-conformant systems can be branded UNIX 03.

The POSIX.1-2001 document is broken into four parts:

XBD: Definitions, terms, and concepts, header file specifications.

XSH: Specifications of functions (i.e., system calls and library functions in actual implementations).

XCU: Specifications of commands and utilities (i.e., the area formerly described by POSIX.2).

XRAT: Informative text on the other parts of the standard.

POSIX.1-2001 is aligned with C99, so that all of the library functions standardized in C99 are also standardized in POSIX.1-2001.

The Single UNIX Specification version 3 (SUSv3) comprises the Base Specifications containing XBD, XSH, XCU, and XRAT as above, plus X/Open Curses Issue 4 version 2 as an extra volume that is not in POSIX.1-2001.

Two Technical Corrigenda (minor fixes and improvements) of the original 2001 standard have occurred: TC1 in 2003 and TC2 in 2004.

POSIX.1-2008, SUSv4

Work on the next revision of POSIX.1/SUS was completed and ratified in 2008. The standard is available online at http://www.unix.org/version4/.

The changes in this revision are not as large as those that occurred for POSIX.1-2001/SUSv3, but a number of new interfaces are added and various details of existing specifications are modified. Many of the interfaces that were optional in POSIX.1-2001 become mandatory in the 2008 revision of the standard. A few interfaces that are present in POSIX.1-2001 are marked as obsolete in POSIX.1-2008, or removed from the standard altogether.

The revised standard is structured in the same way as its predecessor. The Single UNIX Specification version 4 (SUSv4) comprises the Base Specifications containing XBD, XSH, XCU, and XRAT, plus X/Open Curses Issue 7 as an extra volume that is not in POSIX.1-2008.

Again there are two levels of conformance: the baseline POSIX Conformance, and XSI Conformance, which mandates an additional set of interfaces beyond those in the base specification.

In general, where the CONFORMING TO section of a manual page lists POSIX.1-2001, it can be assumed that the interface also conforms to POSIX.1-2008, unless otherwise noted.

Technical Corrigendum 1 (minor fixes and improvements) of this standard was released in 2013.

Technical Corrigendum 2 of this standard was released in 2016.

Further information can be found on the Austin Group web site, http://www.opengroup.org/austin/.

SUSv4 2016 edition

This is equivalent to POSIX.1-2008, with the addition of Technical Corrigenda 1 and 2 and the XCurses specification.

POSIX.1-2017

This revision of POSIX is technically identical to POSIX.1-2008 with Technical Corrigenda 1 and 2 applied.

SUSv4 2018 edition

This is equivalent to POSIX.1-2017, with the addition of the XCurses specification.

The interfaces documented in POSIX.1/SUS are available as manual pages under sections 0p (header files), 1p (commands), and 3p (functions); thus one can write "man 3p open".

## SEE ALSO
getconf(1), confstr(3), pathconf(3), sysconf(3), attributes(7), feature_test_macros(7), libc(7), posixoptions(7), system_data_types(7)


suffixes

title: suffixes(7)

summary: list of file suffixes

text:
# suffixes(7)

## NAME
suffixes - list of file suffixes

## DESCRIPTION
It is customary to indicate the contents of a file with the file suffix, which (typically) consists of a period, followed by one or more letters. Many standard utilities, such as compilers, use this to recognize the type of file they are dealing with. The make(1) utility is driven by rules based on file suffix.

Following is a list of suffixes which are likely to be found on a Linux system.

Suffix

File type

,v

files for RCS (Revision Control System)

-

backup file

.C

C++ source code, equivalent to .cc

.F

Fortran source with cpp(1) directives

or file compressed using freeze

.S

assembler source with cpp(1) directives

.Y

file compressed using yabba

.Z

file compressed using compress(1)

.[0-9]+gf

TeX generic font files

.[0-9]+pk

TeX packed font files

.[1-9]

manual page for the corresponding section

.[1-9][a-z]

manual page for section plus subsection

.a

static object code library

.ad

X application default resource file

.ada

Ada source (may be body, spec, or combination)

.adb

Ada body source

.ads

Ada spec source

.afm

PostScript font metrics

.al

Perl autoload file

.am

automake(1) input file

.arc

arc(1) archive

.arj

arj(1) archive

.asc

PGP ASCII-armored data

.asm

(GNU) assembler source file

.au

Audio sound file

.aux

LaTeX auxiliary file

.avi

(msvideo) movie

.awk

AWK language program

.b

LILO boot loader image

.bak

backup file

.bash

bash(1) shell script

.bb

basic block list data produced by

gcc -ftest-coverage

.bbg

basic block graph data produced by

gcc -ftest-coverage

.bbl

BibTeX output

.bdf

X font file

.bib

TeX bibliographic database, BibTeX input

.bm

bitmap source

.bmp

bitmap

.bz2

file compressed using bzip2(1)

.c

C source

.cat

message catalog files

.cc

C++ source

.cf

configuration file

.cfg

configuration file

.cgi

WWW content generating script or program

.cls

LaTeX Class definition

.class

Java compiled byte-code

.conf

configuration file

.config

configuration file

.cpp

equivalent to .cc

.csh

csh(1) shell script

.cxx

equivalent to .cc

.dat

data file

.deb

Debian software package

.def

Modula-2 source for definition modules

.def

other definition files

.desc

initial part of mail message unpacked with

munpack(1)

.diff

file differences (diff(1) command output)

.dir

dbm data base directory file

.doc

documentation file

.dsc

Debian Source Control (source package)

.dtx

LaTeX package source file

.dvi

TeX's device independent output

.el

Emacs-Lisp source

.elc

compiled Emacs-Lisp source

.eps

encapsulated PostScript

.exp

Expect source code

.f

Fortran source

.f77

Fortran 77 source

.f90

Fortran 90 source

.fas

precompiled Common-Lisp

.fi

Fortran include files

.fig

FIG image file (used by xfig(1))

.fmt

TeX format file

.gif

Compuserve Graphics Image File format

.gmo

GNU format message catalog

.gsf

Ghostscript fonts

.gz

file compressed using gzip(1)

.h

C or C++ header files

.help

help file

.hf

equivalent to .help

.hlp

equivalent to .help

.htm

poor man's .html

.html

HTML document used with the World Wide Web

.hqx

7-bit encoded Macintosh file

.i

C source after preprocessing

.icon

bitmap source

.idx

reference or datum-index file for hypertext

or database system

.image

bitmap source

.in

configuration template, especially for GNU Autoconf

.info

files for the Emacs info browser

.info-[0-9]+

split info files

.ins

LaTeX package install file for docstrip

.itcl

itcl source code;

itcl ([incr Tcl]) is an OO extension of tcl

.java

a Java source file

.jpeg

Joint Photographic Experts Group format

.jpg

poor man's .jpeg

.kmap

lyx(1) keymap

.l

equivalent to .lex or .lisp

.lex

lex(1) or flex(1) files

.lha

lharc archive

.lib

Common-Lisp library

.lisp

Lisp source

.ln

files for use with lint(1)

.log

log file, in particular produced by TeX

.lsm

Linux Software Map entry

.lsp

Common-Lisp source

.lzh

lharc archive

.m

Objective-C source code

.m4

m4(1) source

.mac

macro files for various programs

.man

manual page (usually source rather than formatted)

.map

map files for various programs

.me

Nroff source using the me macro package

.mf

Metafont (font generator for TeX) source

.mgp

MagicPoint file

.mm

sources for groff(1) in mm - format

.mo

Message catalog binary file

.mod

Modula-2 source for implementation modules

.mov

(quicktime) movie

.mp

Metapost source

.mp2

MPEG Layer 2 (audio) file

.mp3

MPEG Layer 3 (audio) file

.mpeg

movie file

.o

object file

.old

old or backup file

.orig

backup (original) version of a file, from patch(1)

.out

output file, often executable program (a.out)

.p

Pascal source

.pag

dbm data base data file

.patch

file differences for patch(1)

.pbm

portable bitmap format

.pcf

X11 font files

.pdf

Adobe Portable Data Format

(use Acrobat/acroread or xpdf)

.perl

Perl source (see .ph, .pl, and .pm)

.pfa

PostScript font definition files, ASCII format

.pfb

PostScript font definition files, binary format

.pgm

portable greymap format

.pgp

PGP binary data

.ph

Perl header file

.php

PHP program file

.php3

PHP3 program file

.pid

File to store daemon PID (e.g., crond.pid)

.pl

TeX property list file or Perl library file

.pm

Perl module

.png

Portable Network Graphics file

.po

Message catalog source

.pod

perldoc(1) file

.ppm

portable pixmap format

.pr

bitmap source

.ps

PostScript file

.py

Python source

.pyc

compiled python

.qt

quicktime movie

.r

RATFOR source (obsolete)

.rej

patches that patch(1) couldn't apply

.rpm

RPM software package

.rtf

Rich Text Format file

.rules

rules for something

.s

assembler source

.sa

stub libraries for a.out shared libraries

.sc

sc(1) spreadsheet commands

.scm

Scheme source code

.sed

sed source file

.sgml

SGML source file

.sh

sh(1) scripts

.shar

archive created by the shar(1) utility

.so

Shared library or dynamically loadable object

.sql

SQL source

.sqml

SQML schema or query program

.sty

LaTeX style files

.sym

Modula-2 compiled definition modules

.tar

archive created by the tar(1) utility

.tar.Z

tar(1) archive compressed with compress(1)

.tar.bz2

tar(1) archive compressed with bzip2(1)

.tar.gz

tar(1) archive compressed with gzip(1)

.taz

tar(1) archive compressed with compress(1)

.tcl

tcl source code

.tex

TeX or LaTeX source

.texi

equivalent to .texinfo

.texinfo

Texinfo documentation source

.text

text file

.tfm

TeX font metric file

.tgz

tar archive compressed with gzip(1)

.tif

poor man's .tiff

.tiff

Tagged Image File Format

.tk

tcl/tk script

.tmp

temporary file

.tmpl

template files

.txt

equivalent to .text

.uu

equivalent to .uue

.uue

binary file encoded with uuencode(1)

.vf

TeX virtual font file

.vpl

TeX virtual property list file

.w

Silvio Levi's CWEB

.wav

wave sound file

.web

Donald Knuth's WEB

.wml

Source file for Web Meta Language

.xbm

X11 bitmap source

.xcf

GIMP graphic

.xml

eXtended Markup Language file

.xpm

X11 pixmap source

.xs

Perl xsub file produced by h2xs

.xsl

XSL stylesheet

.y

yacc(1) or bison(1) (parser generator) files

.z

File compressed using pack(1) (or an old gzip(1))

.zip

zip(1) archive

.zoo

zoo(1) archive

~

Emacs or patch(1) backup file

rc

startup (`run control') file, e.g., .newsrc

## CONFORMING TO
General UNIX conventions.

## BUGS
This list is not exhaustive.

## SEE ALSO
file(1), make(1)