乐趣区

Linux文件IO模型

Linux 文件 I / O 模型 文件阻塞 | 非阻塞

1 普通文件创写读不会阻塞


#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

void write_file(int fd){char buf[]="abcde\n";
    write(fd,buf,sizeof(buf));

    close(fd);
}

void read_file(){
    int fd;
    char *path="./test1.txt";
    char result[20];
    fd=open(path,O_RDONLY);
    read(fd,result,10);
    printf("The content is %s",result);
    close(fd);
}

int create_file(){
    int fd;
    char *path="/home/zhf/test1.txt";
    fd=creat(path,00777);
    return fd;
}

int main(){read_file();


}

2 终端设备和网络读取会阻塞

终端代码

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{char buf[10];
    int n;

    n = read(STDIN_FILENO, buf, 10);   // #define STDIN_FILENO 0   STDOUT_FILENO 1  STDERR_FILENO 2
    if(n < 0){perror("read STDIN_FILENO");
        //printf("%d", errno);
        exit(1);
    }
    write(STDOUT_FILENO, buf, n);

    return 0;
}

服务端

// 服务器端
 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
 
#define MAXLINE 4096
 
int main(int argc, char** argv)
{
    int    listenfd, connfd;
    struct sockaddr_in     servaddr;
    char    buff[4096];
    int     n;
 
    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
    exit(0);
    }
 
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(6666);
 
    if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
    exit(0);
    }
 
    if(listen(listenfd, 10) == -1){printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
    exit(0);
    }
 
    printf("======waiting for client's request======\n");
    while(1){if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1){printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
        continue;
    }
    n = recv(connfd, buff, MAXLINE, 0);
    buff[n] = '\0';
    printf("recv msg from client: %s\n", buff);
    close(connfd);
    }
 
    close(listenfd);
}

使用 nc 测试

nc 192.168.0.3 6666

3 总结

阻塞与非阻塞是对于文件而言 而不是 read,write, 终端和网络文件是阻塞的

退出移动版