Created
January 29, 2012 02:22
-
-
Save cou929/1696826 to your computer and use it in GitHub Desktop.
test of O_NONBLOCK from APUE Chapter 12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/uio.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <string.h> | |
void set_fl(int fd, int flags); | |
void clr_fl(int fd, int flags); | |
char buf[100000]; | |
int main(void) { | |
int ntowrite, nwrite; | |
char *ptr; | |
ntowrite = read(STDIN_FILENO, buf, sizeof(buf)); | |
fprintf(stderr, "read %d byts\n", ntowrite); | |
set_fl(STDOUT_FILENO, O_NONBLOCK); | |
for (ptr = buf; ntowrite > 0; ) { | |
errno = 0; | |
nwrite = write(STDOUT_FILENO, ptr, ntowrite); | |
fprintf(stderr, "nwrite = %d, errno = %d, err_message = '%s'\n", nwrite, errno, strerror(errno)); | |
if (nwrite > 0) { | |
ptr += nwrite; | |
ntowrite -= nwrite; | |
} | |
} | |
clr_fl(STDOUT_FILENO, O_NONBLOCK); | |
return 0; | |
} | |
void set_fl(int fd, int flags) { | |
int val; | |
if ((val = fcntl(fd, F_GETFL, 0)) < 0) { | |
fprintf(stderr, "fcntl F_GETFL error"); | |
exit(1); | |
} | |
val |= flags; /* turn on flags */ | |
if (fcntl(fd, F_SETFL, val) < 0) { | |
fprintf(stderr, "fcntl F_SETFL error"); | |
exit(1); | |
} | |
} | |
void clr_fl(int fd, int flags) { | |
int val; | |
if ((val = fcntl(fd, F_GETFL, 0)) < 0) { | |
fprintf(stderr, "fcntl F_GETFL error"); | |
exit(1); | |
} | |
val &= ~flags; /* turn flags off */ | |
if (fcntl(fd, F_SETFL, val) < 0) { | |
fprintf(stderr, "fcntl F_SETFL error"); | |
exit(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment