coreutils linux终端源码
coreutils-8.5.tar.gz
贴段CAT的大伙瞅瞅
/* cat -- concatenate files and print on the standard output.
Copyright (C) 1988, 1990-1991, 1995-2010 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Differences from the Unix cat:
* Always unbuffered, -u is ignored.
* Usually much faster than other versions of cat, the difference
is especially apparent when using the -v option.
By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#if HAVE_STROPTS_H
# include <stropts.h>
#endif
#if HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#include "system.h"
#include "error.h"
#include "full-write.h"
#include "quote.h"
#include "safe-read.h"
#include "xfreopen.h"
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "cat"
#define AUTHORS \
proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
proper_name ("Richard M. Stallman")
/* Name of input file. May be "-". */
static char const *infile;
/* Descriptor on which input file is open. */
static int input_desc;
/* Buffer for line numbers.
An 11 digit counter may overflow within an hour on a P2/466,
an 18 digit counter needs about 1000y */
#define LINE_COUNTER_BUF_LEN 20
static char line_buf[LINE_COUNTER_BUF_LEN] =
{
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
'\t', '\0'
};
/* Position in `line_buf' where printing starts. This will not change
unless the number of lines is larger than 999999. */
static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;
/* Position of the first digit in `line_buf'. */
static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;
/* Position of the last digit in `line_buf'. */
static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;
/* Preserves the `cat' function's local `newlines' between invocations. */
static int newlines2 = 0;
void
usage (int status)
{
if (status != EXIT_SUCCESS)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
program_name);
fputs (_("\
Concatenate FILE(s), or standard input, to standard output.\n\
\n\
-A, --show-all equivalent to -vET\n\
-b, --number-nonblank number nonempty output lines\n\
-e equivalent to -vE\n\
-E, --show-ends display $ at end of each line\n\
-n, --number number all output lines\n\
-s, --squeeze-blank suppress repeated empty output lines\n\
"), stdout);
fputs (_("\
-t equivalent to -vT\n\
-T, --show-tabs display TAB characters as ^I\n\
-u (ignored)\n\
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
With no FILE, or when FILE is -, read standard input.\n\
"), stdout);
printf (_("\
\n\
Examples:\n\
%s f - g Output f's contents, then standard input, then g's contents.\n\
%s Copy standard input to standard output.\n\
"),
program_name, program_name);
emit_ancillary_info ();
}
exit (status);
}
/* Compute the next line number. */
static void
next_line_num (void)
{
char *endp = line_num_end;
do
{
if ((*endp)++ < '9')
return;
*endp-- = '0';
}
while (endp >= line_num_start);
if (line_num_start > line_buf)
*--line_num_start = '1';
else
*line_buf = '>';
if (line_num_start < line_num_print)
line_num_print--;
}
/* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO.
Return true if successful. */
static bool
simple_cat (
/* Pointer to the buffer, used by reads and writes. */
char *buf,
/* Number of characters preferably read or written by each read and write
call. */
size_t bufsize)
{
/* Actual number of characters read, and therefore written. */
size_t n_read;
/* Loop until the end of the file. */
for (;;)
{
/* Read a block of input. */
n_read = safe_read (input_desc, buf, bufsize);
if (n_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", infile);
return false;
}
/* End of this file? */
if (n_read == 0)
return true;
/* Write this block out. */
{
/* The following is ok, since we know that 0 < n_read. */
size_t n = n_read;
if (full_write (STDOUT_FILENO, buf, n) != n)
error (EXIT_FAILURE, errno, _("write error"));
}
}
}
/* Write any pending output to STDOUT_FILENO.
Pending is defined to be the *BPOUT - OUTBUF bytes starting at OUTBUF.
Then set *BPOUT to OUTPUT if it's not already that value. */
static inline void
write_pending (char *outbuf, char **bpout)
{
size_t n_write = *bpout - outbuf;
if (0 < n_write)
{
if (full_write (STDOUT_FILENO, outbuf, n_write) != n_write)
error (EXIT_FAILURE, errno, _("write error"));
*bpout = outbuf;
}
}
/* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
Return true if successful.
Called if any option more than -u was specified.
A newline character is always put at the end of the buffer, to make
an explicit test for buffer end unnecessary. */
static bool
cat (
/* Pointer to the beginning of the input buffer. */
char *inbuf,
/* Number of characters read in each read call. */
size_t insize,
/* Pointer to the beginning of the output buffer. */
char *outbuf,
/* Number of characters written by each write call. */
size_t outsize,
/* Variables that have values according to the specified options. */
bool show_nonprinting,
bool show_tabs,
bool number,
bool number_nonblank,
bool show_ends,
bool squeeze_blank)
{
/* Last character read from the input buffer. */
unsigned char ch;
/* Pointer to the next character in the input buffer. */
char *bpin;
/* Pointer to the first non-valid byte in the input buffer, i.e. the
current end of the buffer. */
char *eob;
/* Pointer to the position where the next character shall be written. */
char *bpout;
/* Number of characters read by the last read call. */
size_t n_read;
/* Determines how many consecutive newlines there have been in the
input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
etc. Initially 0 to indicate that we are at the beginning of a
new line. The "state" of the procedure is determined by
NEWLINES. */
int newlines = newlines2;
#ifdef FIONREAD
/* If nonzero, use the FIONREAD ioctl, as an optimization.
(On Ultrix, it is not supported on NFS file systems.) */
bool use_fionread = true;
#endif
/* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
is read immediately. */
eob = inbuf;
bpin = eob + 1;
bpout = outbuf;
for (;;)
{
do
{
/* Write if there are at least OUTSIZE bytes in OUTBUF. */
if (outbuf + outsize <= bpout)
{
char *wp = outbuf;
size_t remaining_bytes;
do
{
if (full_write (STDOUT_FILENO, wp, outsize) != outsize)
error (EXIT_FAILURE, errno, _("write error"));
wp += outsize;
remaining_bytes = bpout - wp;
}
while (outsize <= remaining_bytes);
/* Move the remaining bytes to the beginning of the
buffer. */
memmove (outbuf, wp, remaining_bytes);
bpout = outbuf + remaining_bytes;
}
/* Is INBUF empty? */
if (bpin > eob)
{
bool input_pending = false;
#ifdef FIONREAD
int n_to_read = 0;
/* Is there any input to read immediately?
If not, we are about to wait,
so write all buffered output before waiting. */
if (use_fionread
&& ioctl (input_desc, FIONREAD, &n_to_read) < 0)
{
/* Ultrix returns EOPNOTSUPP on NFS;
HP-UX returns ENOTTY on pipes.
SunOS returns EINVAL and
More/BSD returns ENODEV on special files
like /dev/null.
Irix-5 returns ENOSYS on pipes. */
if (errno == EOPNOTSUPP || errno == ENOTTY
|| errno == EINVAL || errno == ENODEV
|| errno == ENOSYS)
use_fionread = false;
else
{
error (0, errno, _("cannot do ioctl on %s"), quote (infile));
newlines2 = newlines;
return false;
}
}
if (n_to_read != 0)
input_pending = true;
#endif
if (!input_pending)
write_pending (outbuf, &bpout);
/* Read more input into INBUF. */
n_read = safe_read (input_desc, inbuf, insize);
if (n_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", infile);
write_pending (outbuf, &bpout);
newlines2 = newlines;
return false;
}
if (n_read == 0)
{
write_pending (outbuf, &bpout);
newlines2 = newlines;
return true;
}
/* Update the pointers and insert a sentinel at the buffer
end. */
bpin = inbuf;
eob = bpin + n_read;
*eob = '\n';
}
else
{
/* It was a real (not a sentinel) newline. */
/* Was the last line empty?
(i.e. have two or more consecutive newlines been read?) */
if (++newlines > 0)
{
if (newlines >= 2)
{
/* Limit this to 2 here. Otherwise, with lots of
consecutive newlines, the counter could wrap
around at INT_MAX. */
newlines = 2;
/* Are multiple adjacent empty lines to be substituted
by single ditto (-s), and this was the second empty
line? */
if (squeeze_blank)
{
ch = *bpin++;
continue;
}
}
/* Are line numbers to be written at empty lines (-n)? */
if (number && !number_nonblank)
{
next_line_num ();
bpout = stpcpy (bpout, line_num_print);
}
}
/* Output a currency symbol if requested (-e). */
if (show_ends)
*bpout++ = '$';
/* Output the newline. */
*bpout++ = '\n';
}
ch = *bpin++;
}
while (ch == '\n');
/* Are we at the beginning of a line, and line numbers are requested? */
if (newlines >= 0 && number)
{
next_line_num ();
bpout = stpcpy (bpout, line_num_print);
}
/* Here CH cannot contain a newline character. */
/* The loops below continue until a newline character is found,
which means that the buffer is empty or that a proper newline
has been found. */
/* If quoting, i.e. at least one of -v, -e, or -t specified,
scan for chars that need conversion. */
if (show_nonprinting)
{
for (;;)
{
if (ch >= 32)
{
if (ch < 127)
*bpout++ = ch;
else if (ch == 127)
{
*bpout++ = '^';
*bpout++ = '?';
}
else
{
*bpout++ = 'M';
*bpout++ = '-';
if (ch >= 128 + 32)
{
if (ch < 128 + 127)
*bpout++ = ch - 128;
else
{
*bpout++ = '^';
*bpout++ = '?';
}
}
else
{
*bpout++ = '^';
*bpout++ = ch - 128 + 64;
}
}
}
else if (ch == '\t' && !show_tabs)
*bpout++ = '\t';
else if (ch == '\n')
{
newlines = -1;
break;
}
else
{
*bpout++ = '^';
*bpout++ = ch + 64;
}
ch = *bpin++;
}
}
else
{
/* Not quoting, neither of -v, -e, or -t specified. */
for (;;)
{
if (ch == '\t' && show_tabs)
{
*bpout++ = '^';
*bpout++ = ch + 64;
}
else if (ch != '\n')
*bpout++ = ch;
else
{
newlines = -1;
break;
}
ch = *bpin++;
}
}
}
}
int
main (int argc, char **argv)
{
/* Optimal size of i/o operations of output. */
size_t outsize;
/* Optimal size of i/o operations of input. */
size_t insize;
size_t page_size = getpagesize ();
/* Pointer to the input buffer. */
char *inbuf;
/* Pointer to the output buffer. */
char *outbuf;
bool ok = true;
int c;
/* Index in argv to processed argument. */
int argind;
/* Device number of the output (file or whatever). */
dev_t out_dev;
/* I-node number of the output. */
ino_t out_ino;
/* True if the output file should not be the same as any input file. */
bool check_redirection = true;
/* Nonzero if we have ever read standard input. */
bool have_read_stdin = false;
struct stat stat_buf;
/* Variables that are set according to the specified options. */
bool number = false;
bool number_nonblank = false;
bool squeeze_blank = false;
bool show_ends = false;
bool show_nonprinting = false;
bool show_tabs = false;
int file_open_mode = O_RDONLY;
static struct option const long_options[] =
{
{"number-nonblank", no_argument, NULL, 'b'},
{"number", no_argument, NULL, 'n'},
{"squeeze-blank", no_argument, NULL, 's'},
{"show-nonprinting", no_argument, NULL, 'v'},
{"show-ends", no_argument, NULL, 'E'},
{"show-tabs", no_argument, NULL, 'T'},
{"show-all", no_argument, NULL, 'A'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* Arrange to close stdout if we exit via the
case_GETOPT_HELP_CHAR or case_GETOPT_VERSION_CHAR code.
Normally STDOUT_FILENO is used rather than stdout, so
close_stdout does nothing. */
atexit (close_stdout);
/* Parse command line options. */
while ((c = getopt_long (argc, argv, "benstuvAET", long_options, NULL))
!= -1)
{
switch (c)
{
case 'b':
number = true;
number_nonblank = true;
break;
case 'e':
show_ends = true;
show_nonprinting = true;
break;
case 'n':
number = true;
break;
case 's':
squeeze_blank = true;
break;
case 't':
show_tabs = true;
show_nonprinting = true;
break;
case 'u':
/* We provide the -u feature unconditionally. */
break;
case 'v':
show_nonprinting = true;
break;
case 'A':
show_nonprinting = true;
show_ends = true;
show_tabs = true;
break;
case 'E':
show_ends = true;
break;
case 'T':
show_tabs = true;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (EXIT_FAILURE);
}
}
/* Get device, i-node number, and optimal blocksize of output. */
if (fstat (STDOUT_FILENO, &stat_buf) < 0)
error (EXIT_FAILURE, errno, _("standard output"));
outsize = io_blksize (stat_buf);
/* Input file can be output file for non-regular files.
fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
on others, so the checking should not be done for those types,
and to allow things like cat < /dev/tty > /dev/tty, checking
is not done for device files either. */
if (S_ISREG (stat_buf.st_mode))
{
out_dev = stat_buf.st_dev;
out_ino = stat_buf.st_ino;
}
else
{
check_redirection = false;
#ifdef lint /* Suppress `used before initialized' warning. */
out_dev = 0;
out_ino = 0;
#endif
}
if (! (number || show_ends || squeeze_blank))
{
file_open_mode |= O_BINARY;
if (O_BINARY && ! isatty (STDOUT_FILENO))
xfreopen (NULL, "wb", stdout);
}
/* Check if any of the input files are the same as the output file. */
/* Main loop. */
infile = "-";
argind = optind;
do
{
if (argind < argc)
infile = argv[argind];
if (STREQ (infile, "-"))
{
have_read_stdin = true;
input_desc = STDIN_FILENO;
if ((file_open_mode & O_BINARY) && ! isatty (STDIN_FILENO))
xfreopen (NULL, "rb", stdin);
}
else
{
input_desc = open (infile, file_open_mode);
if (input_desc < 0)
{
error (0, errno, "%s", infile);
ok = false;
continue;
}
}
if (fstat (input_desc, &stat_buf) < 0)
{
error (0, errno, "%s", infile);
ok = false;
goto contin;
}
insize = io_blksize (stat_buf);
/* Compare the device and i-node numbers of this input file with
the corresponding values of the (output file associated with)
stdout, and skip this input file if they coincide. Input
files cannot be redirected to themselves. */
if (check_redirection
&& stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
&& (input_desc != STDIN_FILENO))
{
error (0, 0, _("%s: input file is output file"), infile);
ok = false;
goto contin;
}
/* Select which version of `cat' to use. If any format-oriented
options were given use `cat'; otherwise use `simple_cat'. */
if (! (number || show_ends || show_nonprinting
|| show_tabs || squeeze_blank))
{
insize = MAX (insize, outsize);
inbuf = xmalloc (insize + page_size - 1);
ok &= simple_cat (ptr_align (inbuf, page_size), insize);
}
else
{
inbuf = xmalloc (insize + 1 + page_size - 1);
/* Why are
(OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN + PAGE_SIZE - 1)
bytes allocated for the output buffer?
A test whether output needs to be written is done when the input
buffer empties or when a newline appears in the input. After
output is written, at most (OUTSIZE - 1) bytes will remain in the
buffer. Now INSIZE bytes of input is read. Each input character
may grow by a factor of 4 (by the prepending of M-^). If all
characters do, and no newlines appear in this block of input, we
will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
If the last character in the preceding block of input was a
newline, a line number may be written (according to the given
options) as the first thing in the output buffer. (Done after the
new input is read, but before processing of the input begins.)
A line number requires seldom more than LINE_COUNTER_BUF_LEN
positions.
Align the output buffer to a page size boundary, for efficency on
some paging implementations, so add PAGE_SIZE - 1 bytes to the
request to make room for the alignment. */
outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN
+ page_size - 1);
ok &= cat (ptr_align (inbuf, page_size), insize,
ptr_align (outbuf, page_size), outsize, show_nonprinting,
show_tabs, number, number_nonblank, show_ends,
squeeze_blank);
free (outbuf);
}
free (inbuf);
contin:
if (!STREQ (infile, "-") && close (input_desc) < 0)
{
error (0, errno, "%s", infile);
ok = false;
}
}
while (++argind < argc);
if (have_read_stdin && close (STDIN_FILENO) < 0)
error (EXIT_FAILURE, errno, _("closing standard input"));
exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
linux内核 0.11版本源码 带中文注释
目录树 下面再给个样例
├─Makefile
│
├─boot
│ bootsect.s
│ head.s
│ setup.s
│
├─fs
│ bitmap.c
│ block_dev.c
│ buffer.c
│ char_dev.c
│ exec.c
│ fcntl.c
│ file_dev.c
│ file_table.c
│ inode.c
│ ioctl.c
│ Makefile
│ namei.c
│ open.c
│ pipe.c
│ read_write.c
│ stat.c
│ super.c
│ truncate.c
│
├─include
│ │ a.out.h
│ │ const.h
│ │ ctype.h
│ │ errno.h
│ │ fcntl.h
│ │ signal.h
│ │ stdarg.h
│ │ stddef.h
│ │ string.h
│ │ termios.h
│ │ time.h
│ │ unistd.h
│ │ utime.h
│ │
│ ├─asm
│ │ io.h
│ │ memory.h
│ │ segment.h
│ │ system.h
│ │
│ ├─linux
│ │ config.h
│ │ fs.h
│ │ hdreg.h
│ │ head.h
│ │ kernel.h
│ │ mm.h
│ │ sched.h
│ │ sys.h
│ │ tty.h
│ │
│ └─sys
│ stat.h
│ times.h
│ types.h
│ utsname.h
│ wait.h
│
├─init
│ main.c
│
├─kernel
│ │ asm.s
│ │ exit.c
│ │ fork.c
│ │ mktime.c
│ │ panic.c
│ │ printk.c
│ │ sched.c
│ │ signal.c
│ │ sys.c
│ │ system_call.s
│ │ vsprintf.c
│ │
│ ├─blk_drv
│ │ blk.h
│ │ floppy.c
│ │ hd.c
│ │ ll_rw_blk.c
│ │ Makefile
│ │ ramdisk.c
│ │
│ ├─chr_drv
│ │ console.c
│ │ keyboard.S
│ │ Makefile
│ │ rs_io.s
│ │ serial.c
│ │ tty_io.c
│ │ tty_ioctl.c
│ │
│ └─math
│ Makefile
│ math_emulate.
│
├─lib
│ close.c
│ ctype.c
│ dup.c
│ errno.c
│ execve.c
│ Makefile
│ malloc.c
│ open.c
│ setsid.c
│ string.c
│ wait.c
│ write.c
│ _exit.c
│
├─mm
│ Makefile
│ memory.c
│ page.s
│
└─tools
build.c
样例 main。c 用sourceinsight软件阅读 很方便
/*
* linux/init/main.c
*
* (C) 1991 Linus Torvalds
*/
#define __LIBRARY__ // 定义该变量是为了包括定义在unistd.h 中的内嵌汇编代码等信息。
#include // *.h 头文件所在的默认目录是include/,则在代码中就不用明确指明位置。
// 如果不是UNIX 的标准头文件,则需要指明所在的目录,并用双引号括住。
// 标准符号常数与类型文件。定义了各种符号常数和类型,并申明了各种函数。
// 如果定义了__LIBRARY__,则还包括系统调用号和内嵌汇编代码_syscall0()等。
#include // 时间类型头文件。其中最主要定义了tm 结构和一些有关时间的函数原形。
/*
* we need this inline - forking from kernel space will result
* in NO COPY ON WRITE (!!!), until an execve is executed. This
* is no problem, but for the stack. This is handled by not letting
* main() use the stack at all after fork(). Thus, no function
* calls - which means inline code for fork too, as otherwise we
* would use the stack upon exit from 'fork()'.
*
* Actually only pause and fork are needed inline, so that there
* won't be any messing with the stack from main(), but we define
* some others too.
*/
/*
* 我们需要下面这些内嵌语句 - 从内核空间创建进程(forking)将导致没有写时复制(COPY ON WRITE)!!!
* 直到一个执行execve 调用。这对堆栈可能带来问题。处理的方法是在fork()调用之后不让main()使用
* 任何堆栈。因此就不能有函数调用 - 这意味着fork 也要使用内嵌的代码,否则我们在从fork()退出
* 时就要使用堆栈了。
* 实际上只有pause 和fork 需要使用内嵌方式,以保证从main()中不会弄乱堆栈,但是我们同时还
* 定义了其它一些函数。
*/
static inline
_syscall0 (int, fork) // 是unistd.h 中的内嵌宏代码。以嵌入汇编的形式调用
// Linux 的系统调用中断0x80。该中断是所有系统调用的
// 入口。该条语句实际上是int fork()创建进程系统调用。
// syscall0 名称中最后的0 表示无参数,1 表示1 个参数。
static inline _syscall0 (int, pause) // int pause()系统调用:暂停进程的执行,直到
// 收到一个信号。
static inline _syscall1 (int, setup, void *, BIOS) // int setup(void * BIOS)系统调用,仅用于
// linux 初始化(仅在这个程序中被调用)。
static inline _syscall0 (int, sync) // int sync()系统调用:更新文件系统。
#include // tty 头文件,定义了有关tty_io,串行通信方面的参数、常数。
#include // 调度程序头文件,定义了任务结构task_struct、第1 个初始任务
// 的数据。还有一些以宏的形式定义的有关描述符参数设置和获取的
// 嵌入式汇编函数程序。
#include // head 头文件,定义了段描述符的简单结构,和几个选择符常量。
#include // 系统头文件。以宏的形式定义了许多有关设置或修改
// 描述符/中断门等的嵌入式汇编子程序。
#include // io 头文件。以宏的嵌入汇编程序形式定义对io 端口操作的函数。
#include // 标准定义头文件。定义了NULL, offsetof(TYPE, MEMBER)。
#include // 标准参数头文件。以宏的形式定义变量参数列表。主要说明了-个
// 类型(va_list)和三个宏(va_start, va_arg 和va_end),vsprintf、
// vprintf、vfprintf。
#include
#include // 文件控制头文件。用于文件及其描述符的操作控制常数符号的定义。
#include // 类型头文件。定义了基本的系统数据类型。
#include // 文件系统头文件。定义文件表结构(file,buffer_head,m_inode 等)。
static char printbuf[1024]; // 静态字符串数组。
extern int vsprintf (); // 送格式化输出到一字符串中(在kernel/vsprintf.c,92 行)。
extern void init (void); // 函数原形,初始化(在168 行)。
extern void blk_dev_init (void); // 块设备初始化子程序(kernel/blk_drv/ll_rw_blk.c,157 行)
extern void chr_dev_init (void); // 字符设备初始化(kernel/chr_drv/tty_io.c, 347 行)
extern void hd_init (void); // 硬盘初始化程序(kernel/blk_drv/hd.c, 343 行)
extern void floppy_init (void); // 软驱初始化程序(kernel/blk_drv/floppy.c, 457 行)
extern void mem_init (long start, long end); // 内存管理初始化(mm/memory.c, 399 行)
extern long rd_init (long mem_start, int length); //虚拟盘初始化(kernel/blk_drv/ramdisk.c,52)
extern long kernel_mktime (struct tm *tm); // 建立内核时间(秒)。
extern long startup_time; // 内核启动时间(开机时间)(秒)。
/*
* This is set up by the setup-routine at boot-time
*/
/*
* 以下这些数据是由setup.s 程序在引导时间设置的(参见第2 章2.3.1 节中的表2.1)。
*/
#define EXT_MEM_K (*(unsigned short *)0x90002) // 1M 以后的扩展内存大小(KB)。
#define DRIVE_INFO (*(struct drive_info *)0x90080) // 硬盘参数表基址。
#define ORIG_ROOT_DEV (*(unsigned short *)0x901FC) // 根文件系统所在设备号。
/*
* Yeah, yeah, it's ugly, but I cannot find how to do this correctly
* and this seems to work. I anybody has more info on the real-time
* clock I'd be interested. Most of this was trial and error, and some
* bios-listing reading. Urghh.
*/
/*
* 是啊,是啊,下面这段程序很差劲,但我不知道如何正确地实现,而且好象它还能运行。如果有
* 关于实时时钟更多的资料,那我很感兴趣。这些都是试探出来的,以及看了一些bios 程序,呵!
*/
#define CMOS_READ(addr) ({ \ // 这段宏读取CMOS 实时时钟信息。
outb_p (0x80 | addr, 0x70);
\ // 0x70 是写端口号,0x80|addr 是要读取的CMOS 内存地址。
inb_p (0x71);
\ // 0x71 是读端口号。
}
)
#define BCD_TO_BIN(val) ((val)=((val)&15) + ((val)>>4)*10) // 将BCD 码转换成数字。
static void time_init (void) // 该子程序取CMOS 时钟,并设置开机时间??startup_time(秒)。
{
struct tm time;
do
{
time.tm_sec = CMOS_READ (0); // 参见后面CMOS 内存列表。
time.tm_min = CMOS_READ (2);
time.tm_hour = CMOS_READ (4);
time.tm_mday = CMOS_READ (7);
time.tm_mon = CMOS_READ (8);
time.tm_year = CMOS_READ (9);
}
while (time.tm_sec != CMOS_READ (0));
BCD_TO_BIN (time.tm_sec);
BCD_TO_BIN (time.tm_min);
BCD_TO_BIN (time.tm_hour);
BCD_TO_BIN (time.tm_mday);
BCD_TO_BIN (time.tm_mon);
BCD_TO_BIN (time.tm_year);
time.tm_mon--;
startup_time = kernel_mktime (&time);
}
static long memory_end = 0; // 机器具有的内存(字节数)。
static long buffer_memory_end = 0; // 高速缓冲区末端地址。
static long main_memory_start = 0; // 主内存(将用于分页)开始的位置。
struct drive_info
{
char dummy[32];
}
drive_info; // 用于存放硬盘参数表信息。
void main (void) /* This really IS void, no error here. */
{ /* The startup routine assumes (well, ...) this */
/* 这里确实是void,并没错。在startup 程序(head.s)中就是这样假设的。 */
// 参见head.s 程序第136 行开始的几行代码。
/*
* Interrupts are still disabled. Do necessary setups, then
* enable them
*/
/*
* 此时中断仍被禁止着,做完必要的设置后就将其开启。
*/
// 下面这段代码用于保存:
// 根设备号 ??ROOT_DEV; 高速缓存末端地址??buffer_memory_end;
// 机器内存数??memory_end;主内存开始地址 ??main_memory_start;
ROOT_DEV = ORIG_ROOT_DEV;
drive_info = DRIVE_INFO;
memory_end = (1 << 20) + (EXT_MEM_K < 16 * 1024 * 1024) // 如果内存超过16Mb,则按16Mb 计。
memory_end = 16 * 1024 * 1024;
if (memory_end > 12 * 1024 * 1024) // 如果内存>12Mb,则设置缓冲区末端=4Mb
buffer_memory_end = 4 * 1024 * 1024;
else if (memory_end > 6 * 1024 * 1024) // 否则如果内存>6Mb,则设置缓冲区末端=2Mb
buffer_memory_end = 2 * 1024 * 1024;
else
buffer_memory_end = 1 * 1024 * 1024; // 否则则设置缓冲区末端=1Mb
main_memory_start = buffer_memory_end; // 主内存起始位置=缓冲区末端;
#ifdef RAMDISK // 如果定义了虚拟盘,则主内存将减少。
main_memory_start += rd_init (main_memory_start, RAMDISK * 1024);
#endif
// 以下是内核进行所有方面的初始化工作。阅读时最好跟着调用的程序深入进去看,实在看
// 不下去了,就先放一放,看下一个初始化调用 -- 这是经验之谈?。
mem_init (main_memory_start, memory_end);
trap_init (); // 陷阱门(硬件中断向量)初始化。(kernel/traps.c,181 行)
blk_dev_init (); // 块设备初始化。 (kernel/blk_dev/ll_rw_blk.c,157 行)
chr_dev_init (); // 字符设备初始化。 (kernel/chr_dev/tty_io.c,347 行)
tty_init (); // tty 初始化。 (kernel/chr_dev/tty_io.c,105 行)
time_init (); // 设置开机启动时间??startup_time(见76 行)。
sched_init (); // 调度程序初始化(加载了任务0 的tr, ldtr) (kernel/sched.c,385)
buffer_init (buffer_memory_end); // 缓冲管理初始化,建内存链表等。(fs/buffer.c,348)
hd_init (); // 硬盘初始化。 (kernel/blk_dev/hd.c,343 行)
floppy_init (); // 软驱初始化。 (kernel/blk_dev/floppy.c,457 行)
sti (); // 所有初始化工作都做完了,开启中断。
// 下面过程通过在堆栈中设置的参数,利用中断返回指令切换到任务0。
move_to_user_mode (); // 移到用户模式。 (include/asm/system.h,第1 行)
if (!fork ())
{ /* we count on this going ok */
init ();
}
/*
* NOTE!! For any other task 'pause()' would mean we have to get a
* signal to awaken, but task0 is the sole exception (see 'schedule()')
* as task 0 gets activated at every idle moment (when no other tasks
* can run). For task0 'pause()' just means we go check if some other
* task can run, and if not we return here.
*/
/* 注意!! 对于任何其它的任务,'pause()'将意味着我们必须等待收到一个信号才会返
* 回就绪运行态,但任务0(task0)是唯一的意外情况(参见'schedule()'),因为任务0 在
* 任何空闲时间里都会被激活(当没有其它任务在运行时),因此对于任务0'pause()'仅意味着
* 我们返回来查看是否有其它任务可以运行,如果没有的话我们就回到这里,一直循环执行'pause()'。
*/
for (;;)
pause ();
}
static int printf (const char *fmt, ...)
// 产生格式化信息并输出到标准输出设备stdout(1),这里是指屏幕上显示。参数'*fmt'指定输出将
// 采用的格式,参见各种标准C 语言书籍。该子程序正好是vsprintf 如何使用的一个例子。
// 该程序使用vsprintf()将格式化的字符串放入printbuf 缓冲区,然后用write()将缓冲区的内容
// 输出到标准设备(1--stdout)。
{
va_list args;
int i;
va_start (args, fmt);
write (1, printbuf, i = vsprintf (printbuf, fmt, args));
va_end (args);
return i;
}
static char *argv_rc[] =
{
"/bin/sh", NULL}; // 调用执行程序时参数的字符串数组。
static char *envp_rc[] =
{
"HOME=/", NULL}; // 调用执行程序时的环境字符串数组。
static char *argv[] =
{
"-/bin/sh", NULL}; // 同上。
static char *envp[] =
{
"HOME=/usr/root", NULL};
void init (void)
{
int pid, i;
// 读取硬盘参数包括分区表信息并建立虚拟盘和安装根文件系统设备。
// 该函数是在25 行上的宏定义的,对应函数是sys_setup(),在kernel/blk_drv/hd.c,71 行。
setup ((void *) &drive_info);
(void) open ("/dev/tty0", O_RDWR, 0); // 用读写访问方式打开设备“/dev/tty0”,
// 这里对应终端控制台。
// 返回的句柄号0 -- stdin 标准输入设备。
(void) dup (0); // 复制句柄,产生句柄1 号 -- stdout 标准输出设备。
(void) dup (0); // 复制句柄,产生句柄2 号 -- stderr 标准出错输出设备。
printf ("%d buffers = %d bytes buffer space\n\r", NR_BUFFERS, NR_BUFFERS * BLOCK_SIZE); // 打印缓冲区块数和总字节数,每块1024 字节。
printf ("Free mem: %d bytes\n\r", memory_end - main_memory_start); //空闲内存字节数。
// 下面fork()用于创建一个子进程(子任务)。对于被创建的子进程,fork()将返回0 值,
// 对于原(父进程)将返回子进程的进程号。所以180-184 句是子进程执行的内容。该子进程
// 关闭了句柄0(stdin),以只读方式打开/etc/rc 文件,并执行/bin/sh 程序,所带参数和
// 环境变量分别由argv_rc 和envp_rc 数组给出。参见后面的描述。
if (!(pid = fork ()))
{
close (0);
if (open ("/etc/rc", O_RDONLY, 0))
_exit (1); // 如果打开文件失败,则退出(/lib/_exit.c,10)。
execve ("/bin/sh", argv_rc, envp_rc); // 装入/bin/sh 程序并执行。
_exit (2); // 若execve()执行失败则退出(出错码2,“文件或目录不存在”)。
}
// 下面是父进程执行的语句。wait()是等待子进程停止或终止,其返回值应是子进程的进程号(pid)。
// 这三句的作用是父进程等待子进程的结束。&i 是存放返回状态信息的位置。如果wait()返回值不
// 等于子进程号,则继续等待。
if (pid > 0)
while (pid != wait (&i))
/* nothing */ ;
// 如果执行到这里,说明刚创建的子进程的执行已停止或终止了。下面循环中首先再创建一个子进程,
// 如果出错,则显示“初始化程序创建子进程失败”的信息并继续执行。对于所创建的子进程关闭所有
// 以前还遗留的句柄(stdin, stdout, stderr),新创建一个会话并设置进程组号,然后重新打开
// /dev/tty0 作为stdin,并复制成stdout 和stderr。再次执行系统解释程序/bin/sh。但这次执行所
// 选用的参数和环境数组另选了一套(见上面165-167 行)。然后父进程再次运行wait()等待。如果
// 子进程又停止了执行,则在标准输出上显示出错信息“子进程pid 停止了运行,返回码是i”,然后
// 继续重试下去…,形成“大”死循环。
while (1)
{
if ((pid = fork ()) < 0)
{
printf ("Fork failed in init\r\n");
continue;
}
if (!pid)
{
close (0);
close (1);
close (2);
setsid ();
(void) open ("/dev/tty0", O_RDWR, 0);
(void) dup (0);
(void) dup (0);
_exit (execve ("/bin/sh", argv, envp));
}
while (1)
if (pid == wait (&i))
break;
printf ("\n\rchild %d died with code %04x\n\r", pid, i);
sync ();
}
_exit (0); /* NOTE! _exit, not exit() */
}