Unix高级编程高级IO部分提到了两个函数,这里把实现写出来:
void set_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0) {
printf("fcntl F_GETFL error\n");
exit(1);
}
val |= flags;
if (fcntl(fd, F_SETFL, val) < 0) {
printf("fcntl F_SETFL error\n");
exit(1);
}
}
void clr_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) == -1) {
printf("fcntl F_GETFL error\n");
exit(1);
}
val &= ~flags;
if (fcntl(fd, F_SETFL, val) == -1) {
printf("fcntl F_SETFL error\n");
exit(1);
}
}
非阻塞代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
char buf[50000];
void set_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0) {
printf("fcntl F_GETFL error\n");
exit(1);
}
val |= flags;
if (fcntl(fd, F_SETFL, val) < 0) {
printf("fcntl F_SETFL error\n");
exit(1);
}
}
void clr_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) == -1) {
printf("fcntl F_GETFL error\n");
exit(1);
}
val &= ~flags;
if (fcntl(fd, F_SETFL, val) == -1) {
printf("fcntl F_SETFL error\n");
exit(1);
}
}
int main()
{
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);
// fcntl(STDOUT_FILENO, F_GETFL, 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);
}
以上代码在 CentOS 6.6 32位上运行