apue2 阅读笔记第三章

第三章--文件IO

1.

creat函数创建文件时权限是O_WRONLY,OPEN函数无此限制。

2.

两张图:

进程打开多个文件时的数据结构关系(进程打开多个文件时的结构关系)

两个独立进程打开同一个文件(两个无关进程打开同一个文件)

当两个进程打开同一个文件时要注意使用锁等方式进行原子操作。

另一个简单的解决方案: 读写时用pread和pwrite(lseek和read write组成的原子操作),创建时用open的O_CREAT 和 O_EXCL选项。

dup2 (a,  b);常用来实现重定向,效果是把b重定向为a,对b的操作实际是操作a。

3.

MGJ)@`M3Z(KA$K0IZYO~UB1

还是图,dup(1)过后进程与打开文件结构及inode节点的关系。

dup函数可以保证返回的文件描述符是可用的重最小的,用 d u p 2则可以用f i l e d e s 2参数指定新描述符的数值。

如果f i l e d e s 2已经打开,则先将其关闭。如若f i l e d e s等于f i l e d e s 2,则d u p 2返回f i l e d e s 2,而不关闭它。

另外:

Another way to duplicate a descriptor is with the fcntl function, which we describe in Section 3.14. Indeed, the call

    dup(filedes);

is equivalent to

    fcntl(filedes, F_DUPFD, 0);

Similarly, the call

    dup2(filedes, filedes2);

is equivalent to

    close(filedes2);
    fcntl(filedes, F_DUPFD, filedes2);
另外,对/dev/fd/xxx操作相当于调用dup函数。
一个比较有意思的练习:

qus:

If you open a file for readwrite with the append flag, can you still read from anywhere in the file using lseek? Can you use lseek to replace existing data in the file? Write a program to verify this.

ans:

You can still lseek and read anywhere in the file, but a write automatically resets the file offset to the end of file before the data is written. This makes it impossible to write anywhere other than at the end of file.

4.

fcntl函数5种功能:

The fcntl function is used for five different purposes.

  1. Duplicate an existing descriptor (cmd = F_DUPFD)

  2. Get/set file descriptor flags (cmd = F_GETFD or F_SETFD)

  3. Get/set file status flags (cmd = F_GETFL or F_SETFL)

  4. Get/set asynchronous I/O ownership (cmd = F_GETOWN or F_SETOWN)

  5. Get/set record locks (cmd = F_GETLK, F_SETLK, or F_SETLKW)

ioctl  函数是I / O操作的杂物箱。不能用本章中其他函数表示的I / O操作通常都能用i o c t l表示。
终端I / O是ioctl  的最大使用方面。#include <unistd.h>        /* System V */
#include <sys/ioctl.h>     /* BSD and Linux */
#include <stropts.h>       /* XSI STREAMS */

int ioctl(int filedes, int request, ...);

Returns: 1 on error, something else if OK

在此原型中,我们表示的只是i o c t l函数本身所要求的头文件。通常,还要求另外的设备专用头文件。

例如,除P O S I X . 1所说明的基本操作之外,终端i o c t l都需要头文件< t e r m i o s . h >。另外要尤其要注意其返回值。

原文地址:https://www.cnblogs.com/liujiahi/p/2247728.html