POSIX

“Portable Operating System Interface”[1] is the collective name of a family of related standards specified by the IEEE to define the application programming interface (API) for software compatible with variants of the Unix operating system.

Waiting for Input or Output

Just a stupid example to remember a couple of peculiarities of the select function.

read_buffer

#include <sys/select.h>
#include <errno.h>
 
int read_buffer(int fd, unsigned char* buffer, int length, unsigned int timeout_ms) {
    int ret, left, bytes = 0;
    fd_set rfds;
    struct timeval sleep;
    struct timeval *psleep = &sleep;
 
    left = length;
    FD_ZERO(&rfds);
    FD_SET(this->serial_fd, &rfds);
 
    if (timeout_ms != 0) {
        sleep.tv_sec = (timeout_ms / 1000);
        sleep.tv_usec = 1000 * (timeout_ms % 1000);
    } else {
        psleep = NULL;
    }
 
    while (true) {
        while (true) {
            if ((ret = select((fd + 1), &rfds, NULL, NULL, psleep)) > 0)
                break;
 
            if (ret == 0)
                return TIMEOUT; 
 
            if ((ret < 0) && (errno != EINTR))
                return SELECT_ERROR;	
        }
 
        if ((ret = read(this->serial_fd, (buffer + bytes), left)) < 0)
            return READ_ERROR;
 
        bytes += ret;
        left  -= ret;
 
        if (bytes >= length)
            break;
 
        if (ret == 0) 
            return EOF;
    }
 
    return bytes;
}

c/posix.txt · Last modified: 2010/08/10 (external edit)
CC Attribution-Noncommercial-Share Alike 3.0 Unported
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0