Welcome, guest | Sign In | My Account | Store | Cart

A simple function to set a file descriptor (i.e. a socket) to blocking or non-blocking mode.

C, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fcntl.h>

/** 
 * Set a file descriptor to blocking or non-blocking mode.
 *
 * @param fd The file descriptor
 * @param blocking 0:non-blocking mode, 1:blocking mode
 *
 * @return 1:success, 0:failure.
 **/
int fd_set_blocking(int fd, int blocking) {
    /* Save the current flags */
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
        return 0;

    if (blocking)
        flags &= ~O_NONBLOCK;
    else
        flags |= O_NONBLOCK;
    return fcntl(fd, F_SETFL, flags) != -1;
}
Created by Emilio Monti on Mon, 6 Sep 2010 (MIT)
C recipes (32)
Emilio Monti's recipes (2)

Required Modules

Other Information and Tasks