码迷,mamicode.com
首页 > 系统相关 > 详细

Linux中的系统IO函数

时间:2019-05-14 13:27:40      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:hid   err   block   hello   hide   lock   inux   fflush   printf   

一、整体大纲

技术图片

 二、常用文件IO函数介绍

    对于Centos7查看系统函数需要安装man手册

[root@centos linuxC]# yum -y install man-pages

1. 常用IO热身:

(1)首先来看下面一个示例:

技术图片
 1 #include<stdio.h>
 2 #include<fcntl.h>
 3 #include<sys/types.h>
 4 #include<unistd.h>
 5 
 6 int main()
 7 {
 8     close(1);
 9     int fd = open("msg.log", O_CREAT|O_TRUNC|O_WRONLY, 0644);
10     printf("hello world\n");
11     //fflush(stdout);
12     close(fd);
13 
14     return 0;
15 }
print_where.c

执行结果如下:

[root@centos linuxC]# gcc print_where.c -o print_where
[root@centos linuxC]# ./print_where
[root@centos linuxC]# cat msg.log

注意:没有打印出预期的"hello world",也没有在文件msg.log中写入"hello world"。

(2)去掉代码中的注释掉的 fflush 再试下:

[root@centos linuxC]# gcc print_where.c -o print_where
[root@centos linuxC]# ./print_where
[root@centos linuxC]# cat msg.log
hello world

注意:没有打印出 "hello world"但是将结果写入到了文件msg.log中。

 (3)结果分析:

技术图片

    系统默认会打开三个文件描述符(stdin,stdout,stderr),在程序中close(1)关掉了标准输出,此时open打开返回的是最小可用的文件描述符,也就是 fd = 1,因此printf本应该打印到文件中,但是close(fd)不会触发buffer刷新,因此既不会输出到屏幕也没有输出到msg.log中。当打开fflush,则会刷新buffer,因此就可以看到msg.log文件中"hello world"。

 

Linux中的系统IO函数

标签:hid   err   block   hello   hide   lock   inux   fflush   printf   

原文地址:https://www.cnblogs.com/xuejiale/p/10777650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!