您的位置:首页 > 运维架构 > Linux

Unix/Linux编程实践教程参考答案-----第二章学习笔记

2014-03-27 12:07 477 查看
2.1key:

1.w

2.man

3. what they are doing.

4.man w 查出其信息来源files为:/var/run/utmp /proc

man -k utmp:utmp的小节编号为:5

man 5 utmp:

w所提供的信息及其含义:

USER login name

TTY the users currently on the machine
FROM
LOGIN@ how long the system has been running
IDLE idle time,
JCPU The JCPU time is the time used by all processes attached to the tty.

It does not include past background jobs, but does include currently

running background jobs.
PCPU The PCPU time is the time used by the current process, named in the "what" field.
WHAT the current process name

5. /prop

2.2key man utnp

The wtmp file records all logins and logouts. Its format is exactly like utmp except that a null username indicates a logout on the associ ated terminal. Furthermore, the terminal name ~ with username shutdown or reboot indicates a system shutdown
or reboot and the pair of terminal names 。 wtmp is maintained by login(1), init(8), and some versions of getty(8)。 None of these programs creates the file, so if it is removed, record-keeping is turned off.

2.3 做个实验,把一个文件复制到/dev/tty: cp1 cp1.c /dev/tty。这是复制的目标文件是一个终端。对终端的读写操作与对一个普通文件进行读写是一样的。接下来做实验,从终端读,这时会从键盘读字符,然后写入到文件中,输入是以回车+<Ctrl-D>作为结束标志的。

key :

在Vim下编辑cp1.c,编译通过。再执行$ ./cp1 cp1.c /dev/tty。这时,在终端中显示cp1.c的内容,表明文件已经成功复制到终端。

执行命令:$ ./cp1 /dev/tty ./test,从终端读入键盘输入的字符,按下<Ctrl-D>后,停止读入并将字符写入到当前目录下的test文件中。

再执行vim test 你会看到你刚才输入的字符就在test上。

2.4标准C函数如fopen、getc、fclose、fgets的实现都包含内核级的缓冲,它们用到了一个结构FILE,并以此为基础构造了类似utmplib的中间层,在头文件中找到结构FILE的成员描述,将其与utmplib.c中的变量做比较。??????

key:

man fopen:查出其头问件是stdio.h

locate stdio.h:找到n个名为stdio.h的头文件

依次查询

在/usr/lib/perl/5.14.2/CORE/nostdio.h文件中找到了对FILE的定义:#define FILE struct _FILE

在/usr/lib/syslinux/com32/include/stdio.h文件中找到了关于FILE的相关描述:

static __inline__ int fileno(FILE * __f)

37 {

38 /* This should really be intptr_t, but size_t should be the same size */

39 return (int)(size_t) __f - 1;

40 }

__extern FILE *fopen(const char *, const char *);

50 struct dev_info;

51 __extern FILE *fopendev(const struct dev_info *, const char *);

52

static __inline__ FILE *fdopen(int __fd, const char *__m)

54 {

55 (void)__m;

56 return __create_file(__fd);

57 }
查询结束没有找到关于FILE的直接描述。

utmplib.c中的变量为:

#define NRECS   16
#define NULLUT  ((struct utmp *)NULL)
#define UTSIZE  (sizeof(struct utmp))

static  char    utmpbuf[NRECS * UTSIZE];                /* storage      */
static  int     num_recs;                               /* num stored   */
static  int     cur_rec;                                /* next to go   */
static  int     fd_utmp = -1;                           /* read from    */

2.5 怎么来确定数据已经被写在磁盘上(不是被缓冲)? 采用缓冲技术时,内核会把要写入磁盘的数据放在缓冲区,然后在它认为合适的时候写入磁盘。阅读相应的联机帮助,找到能够确定地把数据写入磁盘的方法。


数据回写是由内核调度,应用程序无法强制,如果要确保数据写到硬盘,那就要采用RAW模式,自己实现读写操作。

执行指令man sync可以找到相关说明:Force changed blocks to disk, update the super block.

2.6 Unix允许一个文件同时被多个进程打开,也允许一个进程同时打开好几个文件,做多次打开文件的实验:

(1)以读的方式打开文件

(2)以写的方式打开文件

(3)再次以读的方式打开文件

这时有3个文件描述符,接下来:

(4)从第一个文件描述符(以下简称fd)中读20字节,显示读到的内容。

(5)从第二个fd写入“testing 123…”。

(6)从第三个fd读入20字节,显示读到的内容。

2.7联机帮助man中可以查到关于命令、系统调用、系统设备等帮助信息,如何才能了解man的使用方法?在你的系统中,man分为几个小节?它们分别是什么?

1.man man 可以查看man的各种用法

2.12个部分

3.name synopsis description examples overview defaults options exit stattus environment files see also
history

2.8本章提到文件utmp中还包含了一些记录,它们与已登录用户的信息无关,那么它们存放的是什么,各代表什么含义?

/* Values for ut_type field, below */

#define EMPTY 0 /* Record does not contain valid info(formerly known as UT_UNKNOWN on Linux) */

#define RUN_LVL 1 /* Change in system run-level (see init(8)) */

#define BOOT_TIME 2 /* Time of system boot (in ut_tv) */

#define NEW_TIME 3 /* Time after system clock change(in ut_tv) */

#define OLD_TIME 4 /* Time before system clock change (in ut_tv) */

#define INIT_PROCESS 5 /* Process spawned by init(8) */

#define LOGIN_PROCESS 6 /* Session leader process for user login */

#define USER_PROCESS 7 /* Normal process */

#define DEAD_PROCESS 8 /* Terminated process */

#define ACCOUNTING 9 /* Not implemented */

#define UT_LINESIZE 32

#define UT_NAMESIZE 32

#define UT_HOSTSIZE 256

struct exit_status { /* Type for ut_exit, below */

short int e_termination; /* Process termination status */

short int e_exit; /* Process exit status */

};

struct utmp {

short ut_type; /* Type of record */

pid_t ut_pid; /* PID of login process */

char ut_line[UT_LINESIZE]; /* Device name of tty - "/dev/" */

char ut_id[4]; /* Terminal name suffix, or inittab(5) ID */

char ut_user[UT_NAMESIZE]; /* Username */

char ut_host[UT_HOSTSIZE]; /* Hostname for remote login, or kernel version for run-level messages */

struct exit_status ut_exit; /* Exit status of a process marked as DEAD_PROCESS; not used by Linux init(8) */

/* The ut_session and ut_tv fields must be the same size when compiled 32- and 64-bit. This allows data files and shared

memory to be shared between 32- and 64-bit applications. */

#if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32

int32_t ut_session; /* Session ID (getsid(2)), used for windowing */

struct {

int32_t tv_sec; /* Seconds */

int32_t tv_usec; /* Microseconds */

} ut_tv; /* Time entry was made */

#else

long ut_session; /* Session ID */

struct timeval ut_tv; /* Time entry was made */

#endif

int32_t ut_addr_v6[4]; /* Internet address of remote host; IPv4 address uses just ut_addr_v6[0] */

char __unused[20]; /* Reserved for future use */

};

/* Backward compatibility hacks */

#define ut_name ut_user

#ifndef _NO_UT_TIME

#define ut_time ut_tv.tv_sec

#endif

#define ut_xtime ut_tv.tv_sec

#define ut_addr ut_addr_v6[0]

This structure gives the name of the special file associated with the user's terminal, the user's login name, and the time of login in the form of time(2). String fields are terminated by a null byte ('\0') if they are shorter than the size
of the field.

The first entries ever created result from init(8) processing init‐

tab(5). Before an entry is processed, though, init(8) cleans up utmp

by setting ut_type to DEAD_PROCESS, clearing ut_user, ut_host, and

ut_time with null bytes for each record which ut_type is not

DEAD_PROCESS or RUN_LVL and where no process with PID ut_pid exists.

If no empty record with the needed ut_id can be found, init(8) creates

a new one. It sets ut_id from the inittab, ut_pid and ut_time to the

current values, and ut_type to INIT_PROCESS.

mingetty(8) (or agetty(8)) locates the entry by the PID, changes

ut_type to LOGIN_PROCESS, changes ut_time, sets ut_line, and waits for

connection to be established. login(1), after a user has been authen‐

ticated, changes ut_type to USER_PROCESS, changes ut_time, and sets

ut_host and ut_addr. Depending on mingetty(8) (or agetty(8)) and

login(1), records may be located by ut_line instead of the preferable

ut_pid.

When init(8) finds that a process has exited, it locates its utmp entry

by ut_pid, sets ut_type to DEAD_PROCESS, and clears ut_user, ut_host

and ut_time with null bytes.

xterm(1) and other terminal emulators directly create a USER_PROCESS

record and generate the ut_id by using the string that suffix part of

the terminal name (the characters following /dev/[pt]ty). If they find

a DEAD_PROCESS for this ID, they recycle it, otherwise they create a

new entry. If they can, they will mark it as DEAD_PROCESS on exiting

and it is advised that they null ut_line, ut_time, ut_user, and ut_host

as well.

telnetd(8) sets up a LOGIN_PROCESS entry and leaves the rest to

login(1) as usual. After the telnet session ends, telnetd(8) cleans up

utmp in the described way.

The wtmp file records all logins and logouts. Its format is exactly

like utmp except that a null username indicates a logout on the associ‐

ated terminal. Furthermore, the terminal name ~ with username shutdown

or reboot indicates a system shutdown or reboot and the pair of termi‐

nal names |/} logs the old/new system time when date(1) changes it.

wtmp is maintained by login(1), init(8), and some versions of getty(8)

(e.g., mingetty(8) or agetty(8)). None of these programs creates the

2.9 lseek可以将文件指针移动文件的末尾以后,如lseek(fd, 100, SEEK_END)将指针移动到文件末尾再往后100个字节的地方。如果从文件末尾以后100个字节的地方开始读会出现什么情况?从100字节增加到2000字节,再写入“hello”看看会有什么结果,用ls -l来检查文件的长度,再用ls -s试试。

所有打开的文件都有一个当前文件偏移量(current file offset),以下简称为 cfo。cfo 通常是一个非负整数,用于表明文件开始处到文件当前位置的字节数。读写操作通常开始于 cfo,并且使 cfo 增大,增量为读写的字节数。文件被打开时,cfo 会被初始化为 0,除非使用了 O_APPEND 。

使用 lseek 函数可以改变文件的 cfo 。

#include

off_t lseek(int filedes, off_t offset, int whence);

返回值:新的偏移量(成功),-1(失败)

参数 offset 的含义取决于参数 whence:

1. 如果 whence 是 SEEK_SET,文件偏移量将被设置为 offset。

2. 如果 whence 是 SEEK_CUR,文件偏移量将被设置为 cfo 加上 offset,

offset 可以为正也可以为负。

3. 如果 whence 是 SEEK_END,文件偏移量将被设置为文件长度加上 offset,

offset 可以为正也可以为负。

SEEK_SET、SEEK_CUR 和 SEEK_END 是 System V 引入的,在这之前使用的是 0、1 和 2。

lseek 的以下用法返回当前的偏移量:

off_t currpos;

currpos = lseek(fd, 0, SEEK_CUR);

这个技巧也可用于判断我们是否可以改变某个文件的偏移量。如果参数 fd(文件描述符)指定的是 pipe(管道)、FIFO 或者 socket,lseek 返回 -1 并且置 errno 为 ESPIPE。

对于普通文件(regular file),cfo 是一个非负整数。但对于特殊设备,cfo 有可能是负数。因此,我们不能简单地测试 lseek 的返回值是否小于 0 来判断 lseek 成功与否,而应该测试 lseek 的返回值是否等于 -1 来判断 lseek 成功与否。

lseek 仅将 cfo 保存于内核中,不会导致任何 I/O 操作。这个 cfo 将被用于之后的读写操作。

如果 offset 比文件的当前长度更大,下一个写操作就会把文件“撑大(extend)”。这就是所谓的在文件里创造“空洞(hole)”。没有被实际写入文件的所有字节由重复的 0 表示。空洞是否占用硬盘空间是由文件系统(file system)决定的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: