wait.2: Add ESRCH for when pid == INT_MIN
[man-pages.git] / man7 / unix.7
blobfc2834fe4051ba89a4bd1d485d5dc2ccfab208de
1 .\" This man page is Copyright (C) 1999 Andi Kleen <ak@muc.de>,
2 .\" Copyright (C) 2008-2014, Michael Kerrisk <mtk.manpages@gmail.com>,
3 .\" and Copyright (C) 2016, Heinrich Schuchardt <xypron.glpk@gmx.de>
4 .\"
5 .\" %%%LICENSE_START(VERBATIM_ONE_PARA)
6 .\" Permission is granted to distribute possibly modified copies
7 .\" of this page provided the header is included verbatim,
8 .\" and in case of nontrivial modification author and date
9 .\" of the modification is added to the header.
10 .\" %%%LICENSE_END
11 .\"
12 .\" Modified, 2003-12-02, Michael Kerrisk, <mtk.manpages@gmail.com>
13 .\" Modified, 2003-09-23, Adam Langley
14 .\" Modified, 2004-05-27, Michael Kerrisk, <mtk.manpages@gmail.com>
15 .\"     Added SOCK_SEQPACKET
16 .\" 2008-05-27, mtk, Provide a clear description of the three types of
17 .\"     address that can appear in the sockaddr_un structure: pathname,
18 .\"     unnamed, and abstract.
19 .\"
20 .TH UNIX  7 2021-03-22 "Linux" "Linux Programmer's Manual"
21 .SH NAME
22 unix \- sockets for local interprocess communication
23 .SH SYNOPSIS
24 .nf
25 .B #include <sys/socket.h>
26 .B #include <sys/un.h>
27 .PP
28 .IB unix_socket " = socket(AF_UNIX, type, 0);"
29 .IB error " = socketpair(AF_UNIX, type, 0, int *" sv ");"
30 .fi
31 .SH DESCRIPTION
32 The
33 .B AF_UNIX
34 (also known as
35 .BR AF_LOCAL )
36 socket family is used to communicate between processes on the same machine
37 efficiently.
38 Traditionally, UNIX domain sockets can be either unnamed,
39 or bound to a filesystem pathname (marked as being of type socket).
40 Linux also supports an abstract namespace which is independent of the
41 filesystem.
42 .PP
43 Valid socket types in the UNIX domain are:
44 .BR SOCK_STREAM ,
45 for a stream-oriented socket;
46 .BR SOCK_DGRAM ,
47 for a datagram-oriented socket that preserves message boundaries
48 (as on most UNIX implementations, UNIX domain datagram
49 sockets are always reliable and don't reorder datagrams);
50 and (since Linux 2.6.4)
51 .BR SOCK_SEQPACKET ,
52 for a sequenced-packet socket that is connection-oriented,
53 preserves message boundaries,
54 and delivers messages in the order that they were sent.
55 .PP
56 UNIX domain sockets support passing file descriptors or process credentials
57 to other processes using ancillary data.
58 .SS Address format
59 A UNIX domain socket address is represented in the following structure:
60 .PP
61 .in +4n
62 .EX
63 .\" #define UNIX_PATH_MAX    108
64 .\"
65 struct sockaddr_un {
66     sa_family_t sun_family;               /* AF_UNIX */
67     char        sun_path[108];            /* Pathname */
69 .EE
70 .in
71 .PP
72 The
73 .I sun_family
74 field always contains
75 .BR AF_UNIX .
76 On Linux,
77 .I sun_path
78 is 108 bytes in size; see also NOTES, below.
79 .PP
80 Various systems calls (for example,
81 .BR bind (2),
82 .BR connect (2),
83 and
84 .BR sendto (2))
85 take a
86 .I sockaddr_un
87 argument as input.
88 Some other system calls (for example,
89 .BR getsockname (2),
90 .BR getpeername (2),
91 .BR recvfrom (2),
92 and
93 .BR accept (2))
94 return an argument of this type.
95 .PP
96 Three types of address are distinguished in the
97 .I sockaddr_un
98 structure:
99 .IP * 3
100 .IR pathname :
101 a UNIX domain socket can be bound to a null-terminated
102 filesystem pathname using
103 .BR bind (2).
104 When the address of a pathname socket is returned
105 (by one of the system calls noted above),
106 its length is
108     offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
111 .I sun_path
112 contains the null-terminated pathname.
113 (On Linux, the above
114 .BR offsetof ()
115 expression equates to the same value as
116 .IR sizeof(sa_family_t) ,
117 but some other implementations include other fields before
118 .IR sun_path ,
119 so the
120 .BR offsetof ()
121 expression more portably describes the size of the address structure.)
123 For further details of pathname sockets, see below.
124 .IP *
125 .IR unnamed :
126 A stream socket that has not been bound to a pathname using
127 .BR bind (2)
128 has no name.
129 Likewise, the two sockets created by
130 .BR socketpair (2)
131 are unnamed.
132 When the address of an unnamed socket is returned,
133 its length is
134 .IR "sizeof(sa_family_t)" ,
136 .I sun_path
137 should not be inspected.
138 .\" There is quite some variation across implementations: FreeBSD
139 .\" says the length is 16 bytes, HP-UX 11 says it's zero bytes.
140 .IP *
141 .IR abstract :
142 an abstract socket address is distinguished (from a pathname socket)
143 by the fact that
144 .IR sun_path[0]
145 is a null byte (\(aq\e0\(aq).
146 The socket's address in this namespace is given by the additional
147 bytes in
148 .IR sun_path
149 that are covered by the specified length of the address structure.
150 (Null bytes in the name have no special significance.)
151 The name has no connection with filesystem pathnames.
152 When the address of an abstract socket is returned,
153 the returned
154 .I addrlen
155 is greater than
156 .IR "sizeof(sa_family_t)"
157 (i.e., greater than 2), and the name of the socket is contained in
158 the first
159 .IR "(addrlen \- sizeof(sa_family_t))"
160 bytes of
161 .IR sun_path .
162 .SS Pathname sockets
163 When binding a socket to a pathname, a few rules should be observed
164 for maximum portability and ease of coding:
165 .IP * 3
166 The pathname in
167 .I sun_path
168 should be null-terminated.
169 .IP *
170 The length of the pathname, including the terminating null byte,
171 should not exceed the size of
172 .IR sun_path .
173 .IP *
175 .I addrlen
176 argument that describes the enclosing
177 .I sockaddr_un
178 structure should have a value of at least:
181     offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1
184 or, more simply,
185 .I addrlen
186 can be specified as
187 .IR "sizeof(struct sockaddr_un)" .
189 There is some variation in how implementations handle UNIX domain
190 socket addresses that do not follow the above rules.
191 For example, some (but not all) implementations
192 .\" Linux does this, including for the case where the supplied path
193 .\" is 108 bytes
194 append a null terminator if none is present in the supplied
195 .IR sun_path .
197 When coding portable applications,
198 keep in mind that some implementations
199 .\" HP-UX
200 have
201 .I sun_path
202 as short as 92 bytes.
203 .\" Modern BSDs generally have 104, Tru64 and AIX have 104,
204 .\" Solaris and Irix have 108
206 Various system calls
207 .RB ( accept (2),
208 .BR recvfrom (2),
209 .BR getsockname (2),
210 .BR getpeername (2))
211 return socket address structures.
212 When applied to UNIX domain sockets, the value-result
213 .I addrlen
214 argument supplied to the call should be initialized as above.
215 Upon return, the argument is set to indicate the
216 .I actual
217 size of the address structure.
218 The caller should check the value returned in this argument:
219 if the output value exceeds the input value,
220 then there is no guarantee that a null terminator is present in
221 .IR sun_path .
222 (See BUGS.)
224 .SS Pathname socket ownership and permissions
225 In the Linux implementation,
226 pathname sockets honor the permissions of the directory they are in.
227 Creation of a new socket fails if the process does not have write and
228 search (execute) permission on the directory in which the socket is created.
230 On Linux,
231 connecting to a stream socket object requires write permission on that socket;
232 sending a datagram to a datagram socket likewise
233 requires write permission on that socket.
234 POSIX does not make any statement about the effect of the permissions
235 on a socket file, and on some systems (e.g., older BSDs),
236 the socket permissions are ignored.
237 Portable programs should not rely on
238 this feature for security.
240 When creating a new socket, the owner and group of the socket file
241 are set according to the usual rules.
242 The socket file has all permissions enabled,
243 other than those that are turned off by the process
244 .BR umask (2).
246 The owner, group, and permissions of a pathname socket can be changed (using
247 .BR chown (2)
249 .BR chmod (2)).
250 .\" However, fchown() and fchmod() do not seem to have an effect
252 .SS Abstract sockets
253 Socket permissions have no meaning for abstract sockets:
254 the process
255 .BR umask (2)
256 has no effect when binding an abstract socket,
257 and changing the ownership and permissions of the object (via
258 .BR fchown (2)
260 .BR fchmod (2))
261 has no effect on the accessibility of the socket.
263 Abstract sockets automatically disappear when all open references
264 to the socket are closed.
266 The abstract socket namespace is a nonportable Linux extension.
268 .SS Socket options
269 For historical reasons, these socket options are specified with a
270 .B SOL_SOCKET
271 type even though they are
272 .B AF_UNIX
273 specific.
274 They can be set with
275 .BR setsockopt (2)
276 and read with
277 .BR getsockopt (2)
278 by specifying
279 .B SOL_SOCKET
280 as the socket family.
282 .B SO_PASSCRED
283 Enabling this socket option causes receipt of the credentials of
284 the sending process in an
285 .B SCM_CREDENTIALS ancillary
286 message in each subsequently received message.
287 The returned credentials are those specified by the sender using
288 .BR SCM_CREDENTIALS ,
289 or a default that includes the sender's PID, real user ID, and real group ID,
290 if the sender did not specify
291 .B SCM_CREDENTIALS
292 ancillary data.
294 When this option is set and the socket is not yet connected,
295 a unique name in the abstract namespace will be generated automatically.
297 The value given as an argument to
298 .BR setsockopt (2)
299 and returned as the result of
300 .BR getsockopt (2)
301 is an integer boolean flag.
303 .B SO_PASSSEC
304 Enables receiving of the SELinux security label of the peer socket
305 in an ancillary message of type
306 .BR SCM_SECURITY
307 (see below).
309 The value given as an argument to
310 .BR setsockopt (2)
311 and returned as the result of
312 .BR getsockopt (2)
313 is an integer boolean flag.
316 .B SO_PASSSEC
317 option is supported for UNIX domain datagram sockets
318 .\" commit 877ce7c1b3afd69a9b1caeb1b9964c992641f52a
319 since Linux 2.6.18;
320 support for UNIX domain stream sockets was added
321 .\" commit 37a9a8df8ce9de6ea73349c9ac8bdf6ba4ec4f70
322 in Linux 4.2.
324 .BR SO_PEEK_OFF
326 .BR socket (7).
328 .B SO_PEERCRED
329 This read-only socket option returns the
330 credentials of the peer process connected to this socket.
331 The returned credentials are those that were in effect at the time
332 of the call to
333 .BR connect (2)
335 .BR socketpair (2).
337 The argument to
338 .BR getsockopt (2)
339 is a pointer to a
340 .I ucred
341 structure; define the
342 .B _GNU_SOURCE
343 feature test macro to obtain the definition of that structure from
344 .IR <sys/socket.h> .
346 The use of this option is possible only for connected
347 .B AF_UNIX
348 stream sockets and for
349 .B AF_UNIX
350 stream and datagram socket pairs created using
351 .BR socketpair (2).
353 .B SO_PEERSEC
354 This read-only socket option returns the
355 security context of the peer socket connected to this socket.
356 By default, this will be the same as the security context of
357 the process that created the peer socket unless overridden
358 by the policy or by a process with the required permissions.
360 The argument to
361 .BR getsockopt (2)
362 is a pointer to a buffer of the specified length in bytes
363 into which the security context string will be copied.
364 If the buffer length is less than the length of the security
365 context string, then
366 .BR getsockopt (2)
367 returns \-1, sets
368 .I errno
370 .BR ERANGE ,
371 and returns the required length via
372 .IR optlen .
373 The caller should allocate at least
374 .BR NAME_MAX
375 bytes for the buffer initially, although this is not guaranteed
376 to be sufficient.
377 Resizing the buffer to the returned length
378 and retrying may be necessary.
380 The security context string may include a terminating null character
381 in the returned length, but is not guaranteed to do so: a security
382 context "foo" might be represented as either {'f','o','o'} of length 3
383 or {'f','o','o','\\0'} of length 4, which are considered to be
384 interchangeable.
385 The string is printable, does not contain non-terminating null characters,
386 and is in an unspecified encoding (in particular, it
387 is not guaranteed to be ASCII or UTF-8).
389 The use of this option for sockets in the
390 .B AF_UNIX
391 address family is supported since Linux 2.6.2 for connected stream sockets,
392 and since Linux 4.18
393 .\" commit 0b811db2cb2aabc910e53d34ebb95a15997c33e7
394 also for stream and datagram socket pairs created using
395 .BR socketpair (2).
397 .SS Autobind feature
398 If a
399 .BR bind (2)
400 call specifies
401 .I addrlen
403 .IR sizeof(sa_family_t) ,
404 .\" i.e., sizeof(short)
405 or the
406 .BR SO_PASSCRED
407 socket option was specified for a socket that was
408 not explicitly bound to an address,
409 then the socket is autobound to an abstract address.
410 The address consists of a null byte
411 followed by 5 bytes in the character set
412 .IR [0\-9a\-f] .
413 Thus, there is a limit of 2^20 autobind addresses.
414 (From Linux 2.1.15, when the autobind feature was added,
415 8 bytes were used, and the limit was thus 2^32 autobind addresses.
416 The change to 5 bytes came in Linux 2.3.15.)
417 .SS Sockets API
418 The following paragraphs describe domain-specific details and
419 unsupported features of the sockets API for UNIX domain sockets on Linux.
421 UNIX domain sockets do not support the transmission of
422 out-of-band data (the
423 .B MSG_OOB
424 flag for
425 .BR send (2)
427 .BR recv (2)).
430 .BR send (2)
431 .B MSG_MORE
432 flag is not supported by UNIX domain sockets.
434 Before Linux 3.4,
435 .\" commit 9f6f9af7694ede6314bed281eec74d588ba9474f
436 the use of
437 .B MSG_TRUNC
438 in the
439 .I flags
440 argument of
441 .BR recv (2)
442 was not supported by UNIX domain sockets.
445 .B SO_SNDBUF
446 socket option does have an effect for UNIX domain sockets, but the
447 .B SO_RCVBUF
448 option does not.
449 For datagram sockets, the
450 .B SO_SNDBUF
451 value imposes an upper limit on the size of outgoing datagrams.
452 This limit is calculated as the doubled (see
453 .BR socket (7))
454 option value less 32 bytes used for overhead.
455 .SS Ancillary messages
456 Ancillary data is sent and received using
457 .BR sendmsg (2)
459 .BR recvmsg (2).
460 For historical reasons, the ancillary message types listed below
461 are specified with a
462 .B SOL_SOCKET
463 type even though they are
464 .B AF_UNIX
465 specific.
466 To send them, set the
467 .I cmsg_level
468 field of the struct
469 .I cmsghdr
471 .B SOL_SOCKET
472 and the
473 .I cmsg_type
474 field to the type.
475 For more information, see
476 .BR cmsg (3).
478 .B SCM_RIGHTS
479 Send or receive a set of open file descriptors from another process.
480 The data portion contains an integer array of the file descriptors.
482 Commonly, this operation is referred to as "passing a file descriptor"
483 to another process.
484 However, more accurately,
485 what is being passed is a reference to an open file description (see
486 .BR open (2)),
487 and in the receiving process it is likely that a different
488 file descriptor number will be used.
489 Semantically, this operation is equivalent to duplicating
490 .RB ( dup (2))
491 a file descriptor into the file descriptor table of another process.
493 If the buffer used to receive the ancillary data containing
494 file descriptors is too small (or is absent),
495 then the ancillary data is truncated (or discarded)
496 and the excess file descriptors are automatically closed
497 in the receiving process.
499 If the number of file descriptors received in the ancillary data would
500 cause the process to exceed its
501 .B RLIMIT_NOFILE
502 resource limit (see
503 .BR getrlimit (2)),
504 the excess file descriptors are automatically closed
505 in the receiving process.
507 The kernel constant
508 .BR SCM_MAX_FD
509 defines a limit on the number of file descriptors in the array.
510 Attempting to send an array larger than this limit causes
511 .BR sendmsg (2)
512 to fail with the error
513 .BR EINVAL .
514 .BR SCM_MAX_FD
515 has the value 253
516 (or 255 in kernels
517 .\" commit bba14de98753cb6599a2dae0e520714b2153522d
518 before 2.6.38).
520 .B SCM_CREDENTIALS
521 Send or receive UNIX credentials.
522 This can be used for authentication.
523 The credentials are passed as a
524 .I struct ucred
525 ancillary message.
526 This structure is defined in
527 .I <sys/socket.h>
528 as follows:
530 .in +4n
532 struct ucred {
533     pid_t pid;    /* Process ID of the sending process */
534     uid_t uid;    /* User ID of the sending process */
535     gid_t gid;    /* Group ID of the sending process */
540 Since glibc 2.8, the
541 .B _GNU_SOURCE
542 feature test macro must be defined (before including
543 .I any
544 header files) in order to obtain the definition
545 of this structure.
547 The credentials which the sender specifies are checked by the kernel.
548 A privileged process is allowed to specify values that do not match its own.
549 The sender must specify its own process ID (unless it has the capability
550 .BR CAP_SYS_ADMIN ,
551 in which case the PID of any existing process may be specified),
552 its real user ID, effective user ID, or saved set-user-ID (unless it has
553 .BR CAP_SETUID ),
554 and its real group ID, effective group ID, or saved set-group-ID
555 (unless it has
556 .BR CAP_SETGID ).
558 To receive a
559 .I struct ucred
560 message, the
561 .B SO_PASSCRED
562 option must be enabled on the socket.
564 .B SCM_SECURITY
565 Receive the SELinux security context (the security label)
566 of the peer socket.
567 The received ancillary data is a null-terminated string containing
568 the security context.
569 The receiver should allocate at least
570 .BR NAME_MAX
571 bytes in the data portion of the ancillary message for this data.
573 To receive the security context, the
574 .B SO_PASSSEC
575 option must be enabled on the socket (see above).
577 When sending ancillary data with
578 .BR sendmsg (2),
579 only one item of each of the above types may be included in the sent message.
581 At least one byte of real data should be sent when sending ancillary data.
582 On Linux, this is required to successfully send ancillary data over
583 a UNIX domain stream socket.
584 When sending ancillary data over a UNIX domain datagram socket,
585 it is not necessary on Linux to send any accompanying real data.
586 However, portable applications should also include at least one byte
587 of real data when sending ancillary data over a datagram socket.
589 When receiving from a stream socket,
590 ancillary data forms a kind of barrier for the received data.
591 For example, suppose that the sender transmits as follows:
594 .PD 0
595 .IP 1. 3
596 .BR sendmsg (2)
597 of four bytes, with no ancillary data.
598 .IP 2.
599 .BR sendmsg (2)
600 of one byte, with ancillary data.
601 .IP 3.
602 .BR sendmsg (2)
603 of four bytes, with no ancillary data.
607 Suppose that the receiver now performs
608 .BR recvmsg (2)
609 calls each with a buffer size of 20 bytes.
610 The first call will receive five bytes of data,
611 along with the ancillary data sent by the second
612 .BR sendmsg (2)
613 call.
614 The next call will receive the remaining four bytes of data.
616 If the space allocated for receiving incoming ancillary data is too small
617 then the ancillary data is truncated to the number of headers
618 that will fit in the supplied buffer (or, in the case of an
619 .BR SCM_RIGHTS
620 file descriptor list, the list of file descriptors may be truncated).
621 If no buffer is provided for incoming ancillary data (i.e., the
622 .I msg_control
623 field of the
624 .I msghdr
625 structure supplied to
626 .BR recvmsg (2)
627 is NULL),
628 then the incoming ancillary data is discarded.
629 In both of these cases, the
630 .BR MSG_CTRUNC
631 flag will be set in the
632 .I msg.msg_flags
633 value returned by
634 .BR recvmsg (2).
636 .SS Ioctls
637 The following
638 .BR ioctl (2)
639 calls return information in
640 .IR value .
641 The correct syntax is:
645 .BI int " value";
646 .IB error " = ioctl(" unix_socket ", " ioctl_type ", &" value ");"
650 .I ioctl_type
651 can be:
653 .B SIOCINQ
655 .B SOCK_STREAM
656 sockets, this call returns the number of unread bytes in the receive buffer.
657 The socket must not be in LISTEN state, otherwise an error
658 .RB ( EINVAL )
659 is returned.
660 .B SIOCINQ
661 is defined in
662 .IR <linux/sockios.h> .
663 .\" FIXME . http://sources.redhat.com/bugzilla/show_bug.cgi?id=12002,
664 .\" filed 2010-09-10, may cause SIOCINQ to be defined in glibc headers
665 Alternatively,
666 you can use the synonymous
667 .BR FIONREAD ,
668 defined in
669 .IR <sys/ioctl.h> .
670 .\" SIOCOUTQ also has an effect for UNIX domain sockets, but not
671 .\" quite what userland might expect. It seems to return the number
672 .\" of bytes allocated for buffers containing pending output.
673 .\" That number is normally larger than the number of bytes of pending
674 .\" output. Since this info is, from userland's point of view, imprecise,
675 .\" and it may well change, probably best not to document this now.
677 .B SOCK_DGRAM
678 sockets,
679 the returned value is the same as
680 for Internet domain datagram sockets;
682 .BR udp (7).
683 .SH ERRORS
685 .B EADDRINUSE
686 The specified local address is already in use or the filesystem socket
687 object already exists.
689 .B EBADF
690 This error can occur for
691 .BR sendmsg (2)
692 when sending a file descriptor as ancillary data over
693 a UNIX domain socket (see the description of
694 .BR SCM_RIGHTS ,
695 above), and indicates that the file descriptor number that
696 is being sent is not valid (e.g., it is not an open file descriptor).
698 .B ECONNREFUSED
699 The remote address specified by
700 .BR connect (2)
701 was not a listening socket.
702 This error can also occur if the target pathname is not a socket.
704 .B ECONNRESET
705 Remote socket was unexpectedly closed.
707 .B EFAULT
708 User memory address was not valid.
710 .B EINVAL
711 Invalid argument passed.
712 A common cause is that the value
713 .B AF_UNIX
714 was not specified in the
715 .I sun_type
716 field of passed addresses, or the socket was in an
717 invalid state for the applied operation.
719 .B EISCONN
720 .BR connect (2)
721 called on an already connected socket or a target address was
722 specified on a connected socket.
724 .B ENOENT
725 The pathname in the remote address specified to
726 .BR connect (2)
727 did not exist.
729 .B ENOMEM
730 Out of memory.
732 .B ENOTCONN
733 Socket operation needs a target address, but the socket is not connected.
735 .B EOPNOTSUPP
736 Stream operation called on non-stream oriented socket or tried to
737 use the out-of-band data option.
739 .B EPERM
740 The sender passed invalid credentials in the
741 .IR "struct ucred" .
743 .B EPIPE
744 Remote socket was closed on a stream socket.
745 If enabled, a
746 .B SIGPIPE
747 is sent as well.
748 This can be avoided by passing the
749 .B MSG_NOSIGNAL
750 flag to
751 .BR send (2)
753 .BR sendmsg (2).
755 .B EPROTONOSUPPORT
756 Passed protocol is not
757 .BR AF_UNIX .
759 .B EPROTOTYPE
760 Remote socket does not match the local socket type
761 .RB ( SOCK_DGRAM
762 versus
763 .BR SOCK_STREAM ).
765 .B ESOCKTNOSUPPORT
766 Unknown socket type.
768 .B ESRCH
769 While sending an ancillary message containing credentials
770 .RB ( SCM_CREDENTIALS ),
771 the caller specified a PID that does not match any existing process.
773 .B ETOOMANYREFS
774 This error can occur for
775 .BR sendmsg (2)
776 when sending a file descriptor as ancillary data over
777 a UNIX domain socket (see the description of
778 .BR SCM_RIGHTS ,
779 above).
780 It occurs if the number of "in-flight" file descriptors exceeds the
781 .B RLIMIT_NOFILE
782 resource limit and the caller does not have the
783 .BR CAP_SYS_RESOURCE
784 capability.
785 An in-flight file descriptor is one that has been sent using
786 .BR sendmsg (2)
787 but has not yet been accepted in the recipient process using
788 .BR recvmsg (2).
790 This error is diagnosed since mainline Linux 4.5
791 (and in some earlier kernel versions where the fix has been backported).
792 .\" commit 712f4aad406bb1ed67f3f98d04c044191f0ff593
793 In earlier kernel versions,
794 it was possible to place an unlimited number of file descriptors in flight,
795 by sending each file descriptor with
796 .BR sendmsg (2)
797 and then closing the file descriptor so that it was not accounted against the
798 .B RLIMIT_NOFILE
799 resource limit.
801 Other errors can be generated by the generic socket layer or
802 by the filesystem while generating a filesystem socket object.
803 See the appropriate manual pages for more information.
804 .SH VERSIONS
805 .B SCM_CREDENTIALS
806 and the abstract namespace were introduced with Linux 2.2 and should not
807 be used in portable programs.
808 (Some BSD-derived systems also support credential passing,
809 but the implementation details differ.)
810 .SH NOTES
811 Binding to a socket with a filename creates a socket
812 in the filesystem that must be deleted by the caller when it is no
813 longer needed (using
814 .BR unlink (2)).
815 The usual UNIX close-behind semantics apply; the socket can be unlinked
816 at any time and will be finally removed from the filesystem when the last
817 reference to it is closed.
819 To pass file descriptors or credentials over a
820 .BR SOCK_STREAM
821 socket, you must
822 to send or receive at least one byte of nonancillary data in the same
823 .BR sendmsg (2)
825 .BR recvmsg (2)
826 call.
828 UNIX domain stream sockets do not support the notion of out-of-band data.
830 .SH BUGS
831 When binding a socket to an address,
832 Linux is one of the implementations that appends a null terminator
833 if none is supplied in
834 .IR sun_path .
835 In most cases this is unproblematic:
836 when the socket address is retrieved,
837 it will be one byte longer than that supplied when the socket was bound.
838 However, there is one case where confusing behavior can result:
839 if 108 non-null bytes are supplied when a socket is bound,
840 then the addition of the null terminator takes the length of
841 the pathname beyond
842 .IR sizeof(sun_path) .
843 Consequently, when retrieving the socket address
844 (for example, via
845 .BR accept (2)),
846 .\" The behavior on Solaris is quite similar.
847 if the input
848 .I addrlen
849 argument for the retrieving call is specified as
850 .IR "sizeof(struct sockaddr_un)" ,
851 then the returned address structure
852 .I won't
853 have a null terminator in
854 .IR sun_path .
856 In addition, some implementations
857 .\" i.e., traditional BSD
858 don't require a null terminator when binding a socket (the
859 .I addrlen
860 argument is used to determine the length of
861 .IR sun_path )
862 and when the socket address is retrieved on these implementations,
863 there is no null terminator in
864 .IR sun_path .
866 Applications that retrieve socket addresses can (portably) code
867 to handle the possibility that there is no null terminator in
868 .IR sun_path
869 by respecting the fact that the number of valid bytes in the pathname is:
871     strnlen(addr.sun_path, addrlen \- offsetof(sockaddr_un, sun_path))
872 .\" The following patch to amend kernel behavior was rejected:
873 .\" http://thread.gmane.org/gmane.linux.kernel.api/2437
874 .\" Subject: [patch] Fix handling of overlength pathname in AF_UNIX sun_path
875 .\" 2012-04-17
876 .\" And there was a related discussion in the Austin list:
877 .\" http://thread.gmane.org/gmane.comp.standards.posix.austin.general/5735
878 .\" Subject: Having a sun_path with no null terminator
879 .\" 2012-04-18
881 .\" FIXME . Track http://austingroupbugs.net/view.php?id=561
883 Alternatively, an application can retrieve
884 the socket address by allocating a buffer of size
885 .I "sizeof(struct sockaddr_un)+1"
886 that is zeroed out before the retrieval.
887 The retrieving call can specify
888 .I addrlen
890 .IR "sizeof(struct sockaddr_un)" ,
891 and the extra zero byte ensures that there will be
892 a null terminator for the string returned in
893 .IR sun_path :
895 .in +4n
897 void *addrp;
899 addrlen = sizeof(struct sockaddr_un);
900 addrp = malloc(addrlen + 1);
901 if (addrp == NULL)
902     /* Handle error */ ;
903 memset(addrp, 0, addrlen + 1);
905 if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == \-1)
906     /* handle error */ ;
908 printf("sun_path = %s\en", ((struct sockaddr_un *) addrp)\->sun_path);
912 This sort of messiness can be avoided if it is guaranteed
913 that the applications that
914 .I create
915 pathname sockets follow the rules outlined above under
916 .IR "Pathname sockets" .
917 .SH EXAMPLES
918 The following code demonstrates the use of sequenced-packet
919 sockets for local interprocess communication.
920 It consists of two programs.
921 The server program waits for a connection from the client program.
922 The client sends each of its command-line arguments in separate messages.
923 The server treats the incoming messages as integers and adds them up.
924 The client sends the command string "END".
925 The server sends back a message containing the sum of the client's integers.
926 The client prints the sum and exits.
927 The server waits for the next client to connect.
928 To stop the server, the client is called with the command-line argument "DOWN".
930 The following output was recorded while running the server in the background
931 and repeatedly executing the client.
932 Execution of the server program ends when it receives the "DOWN" command.
933 .SS Example output
934 .in +4n
936 $ \fB./server &\fP
937 [1] 25887
938 $ \fB./client 3 4\fP
939 Result = 7
940 $ \fB./client 11 \-5\fP
941 Result = 6
942 $ \fB./client DOWN\fP
943 Result = 0
944 [1]+  Done                    ./server
948 .SS Program source
952  * File connection.h
953  */
955 #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
956 #define BUFFER_SIZE 12
959  * File server.c
960  */
962 #include <stdio.h>
963 #include <stdlib.h>
964 #include <string.h>
965 #include <sys/socket.h>
966 #include <sys/un.h>
967 #include <unistd.h>
968 #include "connection.h"
971 main(int argc, char *argv[])
973     struct sockaddr_un name;
974     int down_flag = 0;
975     int ret;
976     int connection_socket;
977     int data_socket;
978     int result;
979     char buffer[BUFFER_SIZE];
981     /* Create local socket. */
983     connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
984     if (connection_socket == \-1) {
985         perror("socket");
986         exit(EXIT_FAILURE);
987     }
989     /*
990      * For portability clear the whole structure, since some
991      * implementations have additional (nonstandard) fields in
992      * the structure.
993      */
995     memset(&name, 0, sizeof(name));
997     /* Bind socket to socket name. */
999     name.sun_family = AF_UNIX;
1000     strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) \- 1);
1002     ret = bind(connection_socket, (const struct sockaddr *) &name,
1003                sizeof(name));
1004     if (ret == \-1) {
1005         perror("bind");
1006         exit(EXIT_FAILURE);
1007     }
1009     /*
1010      * Prepare for accepting connections. The backlog size is set
1011      * to 20. So while one request is being processed other requests
1012      * can be waiting.
1013      */
1015     ret = listen(connection_socket, 20);
1016     if (ret == \-1) {
1017         perror("listen");
1018         exit(EXIT_FAILURE);
1019     }
1021     /* This is the main loop for handling connections. */
1023     for (;;) {
1025         /* Wait for incoming connection. */
1027         data_socket = accept(connection_socket, NULL, NULL);
1028         if (data_socket == \-1) {
1029             perror("accept");
1030             exit(EXIT_FAILURE);
1031         }
1033         result = 0;
1034         for (;;) {
1036             /* Wait for next data packet. */
1038             ret = read(data_socket, buffer, sizeof(buffer));
1039             if (ret == \-1) {
1040                 perror("read");
1041                 exit(EXIT_FAILURE);
1042             }
1044             /* Ensure buffer is 0\-terminated. */
1046             buffer[sizeof(buffer) \- 1] = 0;
1048             /* Handle commands. */
1050             if (!strncmp(buffer, "DOWN", sizeof(buffer))) {
1051                 down_flag = 1;
1052                 break;
1053             }
1055             if (!strncmp(buffer, "END", sizeof(buffer))) {
1056                 break;
1057             }
1059             /* Add received summand. */
1061             result += atoi(buffer);
1062         }
1064         /* Send result. */
1066         sprintf(buffer, "%d", result);
1067         ret = write(data_socket, buffer, sizeof(buffer));
1068         if (ret == \-1) {
1069             perror("write");
1070             exit(EXIT_FAILURE);
1071         }
1073         /* Close socket. */
1075         close(data_socket);
1077         /* Quit on DOWN command. */
1079         if (down_flag) {
1080             break;
1081         }
1082     }
1084     close(connection_socket);
1086     /* Unlink the socket. */
1088     unlink(SOCKET_NAME);
1090     exit(EXIT_SUCCESS);
1094  * File client.c
1095  */
1097 #include <errno.h>
1098 #include <stdio.h>
1099 #include <stdlib.h>
1100 #include <string.h>
1101 #include <sys/socket.h>
1102 #include <sys/un.h>
1103 #include <unistd.h>
1104 #include "connection.h"
1107 main(int argc, char *argv[])
1109     struct sockaddr_un addr;
1110     int ret;
1111     int data_socket;
1112     char buffer[BUFFER_SIZE];
1114     /* Create local socket. */
1116     data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
1117     if (data_socket == \-1) {
1118         perror("socket");
1119         exit(EXIT_FAILURE);
1120     }
1122     /*
1123      * For portability clear the whole structure, since some
1124      * implementations have additional (nonstandard) fields in
1125      * the structure.
1126      */
1128     memset(&addr, 0, sizeof(addr));
1130     /* Connect socket to socket address. */
1132     addr.sun_family = AF_UNIX;
1133     strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) \- 1);
1135     ret = connect(data_socket, (const struct sockaddr *) &addr,
1136                    sizeof(addr));
1137     if (ret == \-1) {
1138         fprintf(stderr, "The server is down.\en");
1139         exit(EXIT_FAILURE);
1140     }
1142     /* Send arguments. */
1144     for (int i = 1; i < argc; ++i) {
1145         ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
1146         if (ret == \-1) {
1147             perror("write");
1148             break;
1149         }
1150     }
1152     /* Request result. */
1154     strcpy(buffer, "END");
1155     ret = write(data_socket, buffer, strlen(buffer) + 1);
1156     if (ret == \-1) {
1157         perror("write");
1158         exit(EXIT_FAILURE);
1159     }
1161     /* Receive result. */
1163     ret = read(data_socket, buffer, sizeof(buffer));
1164     if (ret == \-1) {
1165         perror("read");
1166         exit(EXIT_FAILURE);
1167     }
1169     /* Ensure buffer is 0\-terminated. */
1171     buffer[sizeof(buffer) \- 1] = 0;
1173     printf("Result = %s\en", buffer);
1175     /* Close socket. */
1177     close(data_socket);
1179     exit(EXIT_SUCCESS);
1183 For examples of the use of
1184 .BR SCM_RIGHTS ,
1186 .BR cmsg (3)
1188 .BR seccomp_unotify (2).
1189 .SH SEE ALSO
1190 .BR recvmsg (2),
1191 .BR sendmsg (2),
1192 .BR socket (2),
1193 .BR socketpair (2),
1194 .BR cmsg (3),
1195 .BR capabilities (7),
1196 .BR credentials (7),
1197 .BR socket (7),
1198 .BR udp (7)