Linux -- fcntl修改文件状态标志

来源:互联网 发布:命运知乎 编辑:程序博客网 时间:2024/06/03 23:49


以下只是使用fcntl改变标准输入的阻塞模式,改成非阻塞的模式

#include <stdio.h>#include <errno.h>#include <string.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h>int main(int argc, char **argv){char buffer[1024] = {0};int flags;flags = fcntl(STDIN_FILENO, F_GETFL);flags |= O_NONBLOCK;if ( fcntl(STDIN_FILENO, F_SETFL, flags) < 0 ){perror("fcntl");return -1;}while (1){memset(buffer, 0, sizeof(buffer));ssize_t size = read(STDIN_FILENO, buffer, sizeof(buffer));if ( size < 0 ){if (errno == EAGAIN ){printf("try again\n");sleep(1);continue;}perror("read");break;}if ( size == 0 ){printf("end of file\n");break;}write(STDOUT_FILENO, buffer, size);}return 0;}


0 0
原创粉丝点击