Skip to content

Instantly share code, notes, and snippets.

@snowleung
Created April 27, 2017 04:37
Show Gist options
  • Save snowleung/b56756871fdf4160a69073e8d7ad4120 to your computer and use it in GitHub Desktop.
Save snowleung/b56756871fdf4160a69073e8d7ad4120 to your computer and use it in GitHub Desktop.
[APUE] NO BLOCK IO
/* [APUE] P356 Polling Example */
/* ./a.out < /var/log/daily.out 2>stderr.out */
/* Environments OSX */
/* gcc -v */
/* Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 */
/* Apple LLVM version 8.0.0 (clang-800.0.42.1) */
/* Target: x86_64-apple-darwin15.6.0 */
/* Thread model: posix */
/* InstalledDir: /Library/Developer/CommandLineTools/usr/bin */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
void
clr_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) == -1)
{
//syslog(LOG_ERR, __FILE__, __LINE__,"fcntl() error : %s", strerror(errno));
exit(1);
}
val &= ~flags;
if (fcntl(fd, F_SETFL, val) == -1)
{
//syslog(LOG_ERR, __FILE__, __LINE__,"fcntl() error : %s", strerror(errno));
exit(1);
}
return;
}
void
set_fl(int fd, int flags)
{
int val;
if ( (val = fcntl(fd, F_GETFL, 0)) < 0)
{
printf("fcntl F_GETFL error");
exit(1);
}
val |= flags;
if (fcntl(fd, F_SETFL, val) < 0)
{
printf("fcntl F_SETFL error");
exit(1);
}
}
char buf[50000];
int
main(void){
int ntowrite, nwrite;
char *ptr;
ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
fprintf(stderr, "read %d bytes \n", ntowrite);
set_fl(STDOUT_FILENO, O_NONBLOCK);
ptr = buf;
while (ntowrite > 0){
errno = 0;
nwrite = write(STDOUT_FILENO, ptr, ntowrite);
fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);
if (nwrite > 0){
ptr += nwrite;
ntowrite -= nwrite;
}
}
clr_fl(STDOUT_FILENO, O_NONBLOCK);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment