Accept () and accept4 ()

Source: Internet
Author: User
Tags new set
Accept

Chapter: Linux programmer Manual (2)
Updated: 2010-09-10

Translation to Yimei

Name

Accept-accept a connection through the set Interface
Summary

# Include esys/types. h>/* See "NOTE "*/# Include esys/socket. h> int accept (intSockfd, Struct sockaddr *ADDR, Socklen_t *Addrlen); # DEFINE _ gnu_source/* Refer to feature_test_macros (7 )*/# Include <sys/socket. h> int accept4 (intSockfd, Struct sockaddr *ADDR, Socklen_t *Addrlen, IntFlags);
Description

Accept() System calls are applied to connectable interfaces (Sock_stream,Sock_seqpacket). It is retrieved from the listening set interface.SockfdThe first connection in the Request queue creates a new connected interface and returns a new file descriptor that references the interface. The newly created interface is not in the listening status. Original set InterfaceSockfdNot affected.

ParametersSockfdIsSocket(2) create a set of interfaces throughBindBind to a local address and callListen(2) It is being monitored.

ParametersADDRIs pointing toSockaddrStructure pointer. This structure is filled into an end interface, also known as the communication layer. Return address ingADDRThe additional format can be set through the interface address family (seeSocket(2) and their respective agreement manual pages. WhenADDRIf it is null, NO content is filled.AddrlenNot used, or null.

ParametersAddrlenIs a "value-return" type parameter. The caller must initialize itADDRThe size (number of bytes) of the structure to which it points. When returned, it indicates the actual size of the end address.

If the provided buffer is too small, the returned address is truncated,AddrlenA value greater than the input value is returned.

If there are no unprocessed connections in the queue and the set of interfaces is not marked as non-blocking,Accept() Will block the current calling process until there is a connection. If there are no unprocessed connections and the set of interfaces is marked as not blocked,Accept() ReturnEagainOrEwouldblockError.

You can useSelect(2) orPoll(2 ). When a connection exists, a readable event is delivered. Further, you can set to sendSigio, SeeSocket(7) to learn more.

For some protocols that require verification, such as decnet,Accept() Only the connection request is retrieved from the queue and verification is not performed. The verification will be performed the next time the new file descriptor is read or written normally, and the newly created interface can be disabled for rejection. Currently, only decnet has such semantics in Linux.

FlagsIs 0, thenAccept4() AndAccept() Functions are the same. BelowFlagsThe bitwise OR operation may be used to obtain different behaviors:

Sock_nonblock
In the newly opened file descriptor settings O_nonblockMark. In Fcntl(2) Save this tag to get the same effect.
Sock_cloexec
Set close-on-exec ( Fd_cloexec. See Open(2) about O_cloexecMark description to understand why this is useful.
Return Value

When the call succeeds, the system calls a non-negative integer file descriptor to represent the accepted set interface. When an error occurs,-1 is returned andErrnoSet to the appropriate value.
Error Handling

In Linux,Accept() (AndAccept4() Put the originalAccept() But not handled network errors are passed to the new set of interfaces. This behavior is different from other BSD implementations. Reliable applications should be calledAccept() And then detect and handle possible network errors of the corresponding protocol.EagainTry again. For TCP/IP, these errors includeEnetdown,Eproto,Enoprotoopt,Ehostdown,Enonet,Ehostunreach,EopnotsuppAndEnetunreach.
Error

EagainOr Ewouldblock
The set of interfaces is marked as non-blocking and no connection is waiting for acceptance. The POSIX.1-2001 allows both errors to be returned at this time, but does not require that both constants must have the same value, so the portable program should check both at the same time.
Ebadf
The descriptor is invalid.
Econnaborted
A connection has been aborted.
Efault
Parameters ADDRIt is not in the writable user address space.
Eintr
Before a valid connection arrives, the system call is interrupted by the signal. For more information, see Signal(7 ).
Einval
The set of interfaces is not connected by the listener, or AddrlenInvalid (negative ).
Einval
( Accept4() In FlagsIs invalid.
Emfile
The maximum number of files opened by a single process is reached.
Enfile
The maximum number of files allowed to be opened by the system is reached.
Enobufs, Enomem
Insufficient free memory. This usually means that the interface memory allocation is limited, not that the system memory is insufficient.
Enotsock
A descriptor is a file, not a socket.
Eopnotsupp
The referenced set interface is not Sock_streamType.
Eproto
Protocol Error.

In additionAccept() May fail due to the following reasons:

Eperm
Firewall Rules prohibit connections.

Also, network errors related to new APIs and Protocols may be returned. Multiple linux kernels, suchEnosr,Esocktnosupport,Eprotonosupport,Etimedout.ErestartsysValue may also need to be concerned.

Version

Accept4() System calls are supported starting from Linux 2.6.28, and glibc is supported starting from version 2.10.
Follow

Accept: POSIX.1-2001, svr4, 4.4bsd ,(Accept() First appeared in 4.2bsd ).

Accept4() Non-standard Linux Extension.

In Linux,Accept() Returned new set of interfacesNoInherit the listener set interface, suchO_nonblockAndO_asyncThis file status. This behavior is inconsistent with the formal BSD interface implementation. The portable program should not assume that the file state is inherited or not inherited, and always set explicitlyAccept() The flag bit required by the returned set of interfaces.

Note:

The POSIX.1-2001 does not require inclusion<Sys/types. h>And this header file is not required in Linux. However, some history (BSD) Implementations require this header file. portable applications should include this file.

InSigioAfter deliverySelect(2) orPoll(2) The connection is deleted due to an asynchronous network error, or called by other threads.Accept(), Do not always wait. If these events occur, the call will be blocked to a new connection.Accept() Never block.SockfdSetO_nonblockMark (seeSocket(7 )).

Socklen_t type

AcceptThe third parameter of () is initially declaredInt *(In libc4 and libc5, and some such as 4.x BSD, sunos4, SGI ). The posix.1g draft wants to change itSize_t *This is the same as SunOS 5, followed by the POSIX draftSocklen_t *And also in single unixspecification and glibc2. Linus Torvalds once said:

"Any reasonable database must ensure that socklen_t and INT have the same length. Otherwise, it will be different from the BSD interface. POSIX initially put itDefinitionIt's size_t, And I (also hope others, but obviously not too many) strongly disagree with them. Defining it as size_t is completely incompatible, especially in 64-bit systems, size_t rarely has the same width as Int. ItRequiredIt has the same width as int, because BSD interface is like this. In any case, the POSIX developer creates socklen_t. They should not touch this thing at first, but once they touch it, it will provide a named type for some profound reasons (maybe some people lose face due to their previous stupid behavior, they will quietly change their behavior names )."

Example

ReferenceBind(2 ).
See

Bind(2 ),Connect(2 ),Listen(2 ),Select(2 ),Socket(2 ),Socket(7)

Http://man7.org/linux/man-pages/dir_all_alphabetic.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.