The Linux file descriptor is set to a non-blocking method

Source: Internet
Author: User

PassFcntlset file Descriptor PropertiesFcntl is the use of F_SETFL,F_GETFL, set the file flags, blocking is set to non-blocking, non-blocking is set to block (this can be encapsulated as a basic function in server development)1. Get the file's flags, which is the second parameter of the Open function:
    Flags = FCNTL (fd,f_getfl,0);


2, set the file flags:
     Fcntl (Fd,f_setfl,flags);


3, add a file of flags, such as the file is blocked, want to set to non-blocking:
      Flags = FCNTL (fd,f_getfl,0);      Flags |= O_nonblock;      Fcntl (Fd,f_setfl,flags);


Or one step the way:

     Fcntl (Socket,f_setfl,fcntl (SOCKET,F_GETFL) | O_nonblock);

4, cancel a file flags, such as the file is non-blocking, want to set up to become blocked: 
    Flags = FCNTL (fd,f_getfl,0);    Flags &= ~o_nonblock;    Fcntl (Fd,f_setfl,flags);

PassSocket APIcreate a non-blockingSocket

</pre><pre name= "code" class= "CPP" > #include <sys/types.h> #include <sys/socket.h>int socket ( int domain,int type,int protocal);


Typeparameter specifies the type of service, the type of service is mainlySock_streamServices,Sock_dgreamservice, it is worth noting that theLinuxKernel version2.6.17up,typeThe parameters can accept the above service and accept the following two symbols as well:Sock_nonblock,sock_cloexec,each of them represents the newly createdsockset to non-blocking, and inForkcall when creating a child process is closed in a child processsocket.However, previous versions are not supported.

1. Create blockingSocket
    int fd_sock = socket (af_inet,sock_stream,0);


2. create a non-blocking socket
    int fd_sock = socket (af_inet,sock_stream| sock_nonblock,0);


The above code indicates that a new socket created is non-blocking

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The Linux file descriptor is set to a non-blocking method

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.