/* nonBlock.c * * From Richard Stevens book, p.140, * [Advanced Prog in Unix Envir.] * * Illlustrating nonblocking I/O * We can issue open/read/write and not block. * Two ways to get nonblocking I/O for a descriptor: * -- when we call open to get the descriptor, we * specify the O_NONBLOCK flag (Sect.3.3) * -- For an already open descriptor, we call fcntl() * to turn on the O_NONBLOCK file status flag. ** ** In file /usr/include/sys/fcntl.h, there is ** the posix style _FNONBLOCK and O_NONBLOCK * * Chee: 2/15/2005 * ***************************************************/ // Steven's own header file, in his Appendix B // #include "ourhdr.h" #include #include #include #include #include #include #include char buf[1000000]; ////////////////////////////////////////////////// // set_fl is defined in p.66, Program 3.5 void set_fl(int fd, int flags) // flag=file status flags to turn on { int val; if ((val = fcntl(fd, F_GETFL, 0)) < 0) perror("fcntl F_GETFL error"); val |= flags; // turn on flags if (fcntl(fd, F_SETFL, val)<0) perror("fcntl F_SETFL error"); } ////////////////////////////////////////////////// // clr_fl is defined in p.66, Program 3.5 // It is just set_fl with one line changed! void clr_fl(int fd, int flags) // flag=file status flags to turn on { int val; if ((val = fcntl(fd, F_GETFL, 0)) < 0) perror("fcntl F_GETFL error"); val &= ~flags; // turn off flags if (fcntl(fd, F_SETFL, val)<0) perror("fcntl F_SETFL error"); } ////////////////////////////////////////////////// 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); // set nonblocking // for (ptr = buf; 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); // clear nonblocking exit(0); }