Linux 开机脚本启动顺序--inittab脚本启动解析

  1. Linux 开机脚本启动顺序: 
  2. 第一步:启动内核
  3. 第二步:执行init (配置文件/etc/inittab)
  4. 第三步:启动相应的脚本,执行inittab脚本,并且执行里面的脚本/etc/init.d rc.sysinit rc.d rc.local。。。
  5. 第四步:启动login登录界面 login
  6. 第五步:在用户登录的时候执行sh脚本的顺序:每次登录的时候都会完全执行的 /etc/profile /etc/bashrc /root/.bashrc /root/.bash_profile
  7.     
  8. inittab脚本:
  9. init的进程号为1,是所有进程的父进程,内核初始化完毕之后,init程序开始运行。其他软件也同时开始运行。init程序通过/etc/inittab文件进行配置。
  10. /etc/inittab文件每一行包括四个字段:label:runlevel:action:process。详细解释如下。
  11. 1.label
  12. 登记项标志符,是一个任意指定的、4个字符以内的序列标号,在本文件内必须唯一。
  13. label是1到4个字符的标签,用来标示输入的值。一些系统只支持2个字符的标签。鉴于此原因,多数人都将标签字符的个数限制在2个以内。该标签可以是任意字符构成的字符串,但实际上,某些特定的标签是常用的,在Red Hat Linux中使用的标签是:
  14. id 用来定义缺省的init运行的级别
  15. si 是系统初始化的进程
  16. ln 其中的n从1~6,指明该进程可以使用的runlevel的级别
  17. ud 是升级进程
  18. ca 指明当按下Ctrl+Alt+Del是运行的进程
  19. pf 指当UPS表明断电时运行的进程
  20. pr 是在系统真正关闭之前,UPS发出电源恢复的信号时需要运行的进程
  21. x 是将系统转入X终端时需要运行的进程
  22.  
  23. 2.runlevels
  24. 系统运行级,即执行登记项的init级别。用于指定相应的登记项适用于哪一个运行级,即在哪一个运行级中被处理。如果该字段为空,那么相应的登记项将适用于所有的运行级。在该字段中,可以同时指定一个或多个运行级,其中各运行级分别以数字0, 1, 2, 3, 4, 5, 6或字母a, b, c表示,且无须对其进行分隔。
  25. 0-->Halt,关闭系统.
  26. 1-->单用户,在grub启动时加上为kernel加上参数single即可进入此运行等级
  27. 2-->无网络多用户模式.
  28. 3-->有网络多用户模式.
  29. 4-->有网络多用户模式.
  30. 5-->X模式
  31. 6-->reboot重启系统
  32. S/s-->同运行等级1
  33. a,b,c-->自定义等级,通常不使用.
  34.  
  35. 3.action
  36. 表示进入对应的runlevel时,init应该运行process字段的命令的方式,有效的action值如下。
  37. boot:只有在引导过程中,才执行该进程,但不等待该进程的结束。当该进程死亡时,也不重新启动该进程。
  38. bootwait:只有在引导过程中,才执行该进程,并等待进程的结束。当该进程死亡时,也不重新启动该进程。实际上,只有在系统被引导后,并从单用户模式进入多用户模式时,这些登记项才被处理;如果系统的默认运行级设置为2(即多用户模式),那么这些登记项在系统引导后将马上被处理。
  39. initdefault:指定系统的默认运行级。系统启动时,init将首先查找该登记项,如果存在,init将依据此决定系统最初要进入的运行级。具体来说,init将指定登记项"run_level"字段中的最大数字(即最高运行级)为当前系统的默认运行级;如果该字段为空,那么将其解释为"0123456",并以"6"作为默认运行级。如果不存在该登记项,那么init将要求用户在系统启动时指定一个最初的运行级。
  40. off:如果相应的进程正在运行,那么就发出一个告警信号,等待20秒后,再通过关闭信号强行终止该进程。如果相应的进程并不存在,那么就忽略该登记项。
  41. once:启动相应的进程,但不等待该进程结束便继续处理/etc/inittab文件中的下一个登记项;当该进程终止时,init也不重新启动该进程。在从一个运行级进入另一个运行级时,如果相应的进程仍然在运行,那么init就不重新启动该进程。
  42. ondemand:与"respawn"的功能完全相同,但只用于运行级为a、b或c的登记项。
  43. powerfail:只在init接收到电源失败信号时,才执行该进程,但不等待该进程结束。
  44. powerwait:只在init接收到电源失败信号时,才执行该进程,并在继续对/etc/inittab文件进行任何处理前等待该进程结束。
  45. respawn:如果相应的进程还不存在,那么init就启动该进程,同时不等待该进程的结束就继续扫描/etc/inittab文件;当该进程终止时,init将重新启动该进程。如果相应的进程已经存在,那么init将忽略该登记项并继续扫描/etc/inittab文件。
  46. sysinit:只有在启动或重新启动系统并首先进入单用户模式时,init才执行这些登记项。而在系统从运行级1~6进入单用户模式时,init并不执行这些登记项。"action"字段为"sysinit"的登记项在"run_level"字段不指定任何运行级。
  47. wait:启动进程并等待其结束,然后再处理/etc/inittab文件中的下一个登记项。
  48. ctrlaltdel:用户在控制台键盘上按下Ctrl+Alt+Del组合键时,允许init重新启动系统。注意,如果该系统放在一个公共场所,系统管理员可将Ctrl+Alt+Del组合键配置为其他行为,比如忽略等。
  49.  
  50. 4.process
  51. 具体应该执行的命令。并负责在退出运行级时将其终止(当然在进入的runlevel中仍要运行的程序除外)。当运行级别改变,并且正在运行的程序并没有在新的运行级别中指定需要运行时,那么init会先发送一个SIGTERM 信号终止,然后是SIGKILL。
  52.  
  53. 5.实例分析:
  54. /*************************/etc/inittab***********************************/
  55. //将系统切换到 initdefault 操作所定义的运行级别即运行级别5。我们可以将运行级别看作是系统的状态。运行级别 0 定义了系统挂起状态,运行级别 1 是单用户模式。运行级别 2 到 5 是多用户状态,运行级别 6 表示重启
  56. id:5:initdefault:
  57.  
  58. //sysinit表示在进行其他工作之前先完成系统初始化.init在处理其它运行等级的脚本之前,首先会执行这一行.是系统的初始化进程.用于设置主机名,挂载文件系统,启动交换分区等.
  59. //rcS脚本会调用/etc/rcS.d目录下的所有脚本进行初始化
  60. si::sysinit:/etc/init.d/rcS //在运行boot或bootwait进程之前运行系统初始化的进程
  61.  
  62. //下条语句可以让系统在重新启动、进入单用户模式的时候提示输入超级用户密码。
  63. //S同运行等级1,并等待其结束,然后再处理/etc/inittab文件中的下一个登记项。
  64. ~~:S:wait:/sbin/sulogin 
  65.  
  66. //当运行级别为5时,以5为参数运行/etc/rc5.d下的脚本,init将等待其返回(wait)
  67. //rc.sysinit,rcS,rc这些都是shell的脚本,完成大量的系统初始化的工作。
  68. //主要工作包括:激活交换分区,检查磁盘,加载硬件模块以及其它一些需要优先执行任务。
  69. //执行rc脚本,传入参数为0-6,即会调用/etc/rc0.d-rc6.d目录下的所有文件
  70. //initdefault 指定默认的 init 级别是 5(多用户模式)。在定义初始的运行级别之后,则调用rc脚本以及参数5(运行级别)来启动系统,即rc脚本(参数5)会调用/etc/rc5.d下的所有脚本。
  71. l0:0:wait:/etc/init.d/rc 0 //使用级别0运行此程序
  72. l1:1:wait:/etc/init.d/rc 1
  73. l2:2:wait:/etc/init.d/rc 2
  74. l3:3:wait:/etc/init.d/rc 3
  75. l4:4:wait:/etc/init.d/rc 4
  76. //会运行该/etc/rc5.d下的3个脚本:
  77. //S10telnetd脚本:开启telnetd服务 start-stop-daemon --start --quiet --exec $telnetd
  78. //S20syslog脚本:开启syslog服务start-stop-daemon -S -b -n syslogd -a /sbin/syslogd -- -n $SYSLOG_ARGS start-stop-daemon -S -b -n klogd -a /sbin/klogd -- -n
  79. //S99rmnologin脚本:删除/etc/nologin文件 rm -f /etc/nologin /etc/nologin.boot
  80. l5:5:wait:/etc/init.d/rc 5
  81. l6:6:wait:/etc/init.d/rc 6
  82.  
  83. z6:6:respawn:/sbin/sulogin//脚本运行等级为6时才执行 
  84.  
  85. //在2、3、4、5级别上以ttyX为参数执行/sbin/mingetty程序,打开ttyX终端用于用户登录,
  86. //如果进程退出则再次运行mingetty程序(respawn),所以登录出错时,接着登录
  87. //缺省波特率是115200
  88. S2:2345:respawn:/sbin/mingetty ttyS2 //修改了mingetty和login程序,系统就可以在自动登录了
  89.  
  90.  
  91. /*************************etc/init.d/rcS***********************************/
  92. //设置PATH,runlevel,prevlevel环境变量,并export
  93. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  94. runlevel=S
  95. prevlevel=N
  96. umask 022 //缺省的文件权限
  97. export PATH runlevel prevlevel
  98.  
  99. if [ -x /sbin/unconfigured.sh ]//检查/sbin/unconfigured.sh是否可执行
  100. then
  101.   /sbin/unconfigured.sh//如果可执行就执行unconfigured.sh,我的根文件系统不存在此文件
  102. fi
  103.  
  104. //执行default目录下的rcS,设置一些变量
  105. //即source /etc/default/rcS
  106. . /etc/default/rcS
  107.  
  108. //trap可以使你在脚本中捕捉信号。该命令的一般形式为:trap name signal(s)
  109. //name是捕捉到信号以后所采取的一系列操作。实际应用中, name一般是一个专门来处理所捕捉信号的函数。
  110. //name需要用双引号( “ ” )引起来。signal就是待捕捉的信号。
  111. //这里就是捕捉INT QUIT TSTP三个信号,执行“:”,实际就是忽略这三个信号,防止脚本执行时使用ctrl-C 就退出脚本
  112. trap ":" INT QUIT TSTP
  113.  
  114. //将执行/etc/init.d中rc,传入参数为“S”,目的就是为了执行/etc/init.d/rcS.d目录下的所有脚本文件,都是连接到/etc/init.d/目录下的链接
  115. //S02banner脚本建立tty设备节点:/bin/mknod -m 0666 /dev/tty c 5 0
  116. //S03sysfs脚本挂载proc和sysfs文件系统:mount -t proc proc /proc mount sysfs /sys -t sysfs
  117. //S03udev脚本:开启udev服务,后台运行udevd程序:/sbin/udevd -d
  118. //S06alignment脚本,输出cpu信息到proc文件系统
  119. //S10checkroot脚本
  120. //S20modutils.sh脚本:insmod module
  121. //S30ramdisk脚本:
  122. //S35mountall.sh脚本:挂载Mount all filesystems
  123. //S37populate-volatile.sh脚本
  124. //S38devpts.sh脚本:挂载mount -t devpts devpts /dev/pts
  125. //S39hostname.sh脚本:输出主机名称(arago)写入/etc/hostname文件:hostname -F /etc/hostname
  126. //S40networking脚本:开启网络服务
  127. //S45mountnfs.sh脚本:挂载nfs
  128. //S55bootmisc.sh脚本:
  129. //S98configure脚本:opkg-cl configure
  130. //S99finish.sh脚本:结束脚本
  131. exec /etc/init.d/rc S 
  132.  
  133. //若rc.boot是目录,则执行rc.boot所有的脚本程序
  134. [ -d /etc/rc.boot ] && run-parts /etc/rc.boot
  135.  
  136. //若setup.sh可执行,就执行,没有此程序
  137. if [ -x /sbin/setup.sh ]
  138. then
  139.   /sbin/setup.sh
  140. fi
  141.  
  142.  
  143. /*************************etc/init.d/rc***********************************/
  144. //这个脚本作用主要是运行/etc/rcS.d目录下的文件,
  145. //其中在 /etc/rcS.d/ 的目录下有一个 README 文本来说明该 /etc/rcS.d/ 目录下脚本的作用:
  146. //即 /etc/rcS.d/ 中是一些到 /etc/init.d/ 中脚本的符号连接。
  147. //执行完 /etc/rcS.d/ 中的脚本后,触发相应的 runlevel 事件,开始运行 /etc/rc.conf 脚本
  148. . /etc/default/rcS
  149. export VERBOSE //etc/default/rcS这个脚本中定义的VERBOSE=no
  150.  
  151. startup_progress() {
  152.     step=$(($step + $step_change))
  153.     if [ "$num_steps" != "0" ]; then
  154.         progress=$((($step * $progress_size / $num_steps) + $first_step))
  155.     else
  156.         progress=$progress_size
  157.     fi
  158.     if type psplash-write >/dev/null 2>&1; then
  159.         TMPDIR=/mnt/.psplash psplash-write "PROGRESS $progress" || true
  160.     fi
  161. }
  162.  
  163.  
  164. startup() {
  165.   [ "$VERBOSE" = very ] && echo "INIT: Running $@..."//VERBOSE=no,所以后边的不打印
  166.  
  167.     //以.sh结尾的脚本是必须执行的脚本,不是以.sh结尾的脚本服务是可以开启或关闭的,通过start或stop参数
  168.   case "$1" in//传入的第一个参数是要执行的文件名,第二个参数是start
  169.     *.sh)
  170.         (//若文件名是以.sh结尾的则执行这个脚本
  171.             trap - INT QUIT TSTP
  172.             scriptname=$1
  173.             shift
  174.             . $scriptname //执行这个脚本,不带参数
  175.         )
  176.         ;;
  177.     *)//若不是以.sh结尾的
  178.         /*实际上rc进程调用的脚本都称为初始化脚本。每个在/etc/init.d下的脚本都可以在执行时带上以下参数,如:start、stop、restart、pause、zap、status、ineed、iuse、needsme、usesme或者broken。
  179.         要启动、停止或者重启一个服务(和所有依赖于它的服务),应该用参数start、stop和restart。*/
  180.         "$@"//执行这个脚本带参数,比如传入的是$@=“/etc/rcS.d/S02banner start”,即带start参数执行这个脚本,这样可以灵活的控制服务的start或者stop
  181.         ;;
  182.   esac
  183.   startup_progress
  184. }
  185.  
  186.     //忽略这三个信号,防止脚本执行时使用ctrl-C 就退出脚本
  187.   trap ":" INT QUIT TSTP
  188.     
  189.     //stty用于设置终端特性。在命令行中设置一个stty选项,一般格式为:stty name character
  190.     //以下将退格设置为^ H:stty erase '\^H',即ctrl+H在此脚本中是退格键
  191.   //设置终端,将 CR 字符映射为 NL 字符,避免阶梯效应
  192.   stty onlcr 0>&1
  193.  
  194.   //Now find out what the current and what the previous runlevel are.
  195.   runlevel=$RUNLEVEL
  196.   //得到第一个参数是“S”,表示等级1,得到当前运行等级1,runlevel=S
  197.   [ "$1" != "" ] && runlevel=$1
  198.   if [ "$runlevel" = "" ]//运行等级为空的话,则退出
  199.   then
  200.     echo "Usage: $0 <runlevel>" >&2
  201.     exit 1
  202.   fi
  203.   previous=$PREVLEVEL
  204.   [ "$previous" = "" ] && previous=N
  205.  
  206.     //传入参数是S的话,则$runleve=S $previous=N
  207.   export runlevel previous
  208.  
  209.   //若$runlevel=“S”,即检查rcS.d是否为目录。
  210.   if [ -d /etc/rc$runlevel.d ]
  211.   then
  212.     //rcS.d是目录
  213.     PROGRESS_STATE=0
  214.  
  215.     //Split the remaining portion of the progress bar into thirds
  216.     progress_size=$(((100 - $PROGRESS_STATE) / 3))//progress_size = 100/3 =33
  217.  
  218.     case "$runlevel" in//runlevel=S
  219.         0|6)
  220.             first_step=-100
  221.             progress_size=100
  222.             step_change=1
  223.             ;;
  224.      S)
  225.             //Begin where the initramfs left off and use 2/3of the remaining space
  226.             first_step=$PROGRESS_STATE ///progress_size = 100/3 =33
  227.             progress_size=$(($progress_size * 2))//progress_size=66
  228.             step_change=1
  229.             ;;
  230.         *)
  231.             //Begin where rcS left off and use the final 1/3 ofthe space (by leaving progress_size unchanged)
  232.             first_step=$(($progress_size * 2 + $PROGRESS_STATE))
  233.             step_change=1
  234.             ;;
  235.     esac
  236.  
  237.     num_steps=0
  238.     for s in /etc/rc$runlevel.d/[SK]*; //s取/etc/rcS.d目录下以S或K开头的文件名
  239.     do
  240.         //这句话的含义去掉变量s中所有的/etc/rcS.d/S??的部分
  241.         //例:s=/etc/rc$runlevel.d/S10checkroot,那么去掉/etc/rc$runlevel.d/K??部分后,s为checkroot
  242.     case "${s##/etc/rc$runlevel.d/S??}" in
  243.         gdm|xdm|kdm|reboot|halt)//若s剩下的文件名中为这五个则跳出for语句
  244.             break
  245.             ;;
  246.     esac
  247.     num_steps=$(($num_steps + 1))//num_steps递加,表示查找到此目录下/etc/rcS.d有多少个脚本
  248.   done//for语句结束
  249.   
  250.   step=0
  251.     //首先运行KILL脚本
  252.     if [ $previous != N ]//由于$previous=N,所以以下不执行
  253.     then
  254.         for i in /etc/rc$runlevel.d/K[0-9][0-9]*//取以K开头的文件名
  255.         do
  256.             //检查是否为常规文件
  257.             [ ! -f $i ] && continue
  258.             //Stop the service.
  259.             startup $i stop
  260.         done
  261.     fi
  262.  
  263.     //然后运行这个级别的START脚本
  264.     for i in /etc/rc$runlevel.d/S*//取得S开头的脚本
  265.     do
  266.         [ ! -f $i ] && continue//检查是否为常规文件,不是则进行下次循环
  267.  
  268.         if [ $previous != N ] && [ $previous != S ]//由于$previous=N,所以此if语句不执行
  269.         then
  270.             //Find start script in previous runlevel and stop script in this runlevel.
  271.             suffix=${i#/etc/rc$runlevel.d/S[0-9][0-9]}//获得i文件名的后缀,假如是S10checkroot,则suffix=checkroot
  272.             stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix //得到stop文件名,假如/etc/rc$runlevel.d/K[0-9][0-9]checkroot
  273.             previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
  274.             //如果有起始脚本,并且没有停止脚本,则不进行这项服务,continue继续下一次循环
  275.             [ -f $previous_start ] && [ ! -f $stop ] && continue
  276.         fi
  277.         
  278.         case "$runlevel" in//runlevel = S
  279.             0|6)
  280.                 startup $i stop
  281.                 ;;
  282.             *)
  283.                 startup $i start//调用start函数,参数就是脚本名称
  284.                 ;;
  285.         esac
  286.     done//for循环结束
  287.     
  288.   fi
  289.  
  290.  
  291. /*************************etc/profile***********************************/
  292. //为启动shell设定一些环境变量
  293. PATH="/usr/local/bin:/usr/bin:/bin" 
  294. EDITOR="/bin/vi"            //needed for packages like cron
  295. test -z "$TERM" && TERM="vt100"    //Basic terminal capab. For screen etc.
  296.  
  297. //若此文件存在,则设置时区
  298. if [ ! -e /etc/localtime ]; then
  299.     TZ="UTC"                
  300.     export TZ
  301. fi
  302.  
  303. //显示用户ID是否为0,是0则设置用户的PATH路径
  304. if [ "`id -u`" -eq 0 ]; then
  305.    PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin:
  306. fi
  307.  
  308. //设置环境变量PS1
  309. if [ "$PS1" ]; then
  310.    PS1='\u@\h:\w\$ '
  311. fi
  312.  
  313. // /etc/profile.d是否为目录
  314. if [ -d /etc/profile.d ]; then
  315.   for i in /etc/profile.d/*.sh /*遍历目录下所有以.sh结尾的脚本文件,并执行*/
  316.   do
  317.     if [ -r $i ]; then
  318.       . $i
  319.     fi
  320.   done
  321.   unset i
  322. fi
  323.  
  324. //可以设置登录后自动运行的APP
  325. . /etc/init.d/autorun-f    
  326.  
  327. export PATH PS1 OPIEDIR QPEDIR QTDIR EDITOR TERM
  328.  
  329. umask 022
  330.  
  331.  
  332. /*********************************************************mingetty.c**********************************************/
  333. /* name of this program (argv[0]) */
  334. static char *progname;
  335. /* on which tty line are we sitting? (e.g. tty1) */
  336. static char *tty;
  337. /* some information about this host */
  338. static struct utsname uts;
  339. /* the hostname */
  340. static char hn[MAXHOSTNAMELEN + 1];
  341. /* process and session ID of this program */
  342. static pid_t pid, sid;
  343. /* login program invoked */
  344. static char *loginprog = "/bin/login";
  345. /* Do not send a reset string to the terminal. */
  346. static int noclear = 0;
  347. /* Do not print a newline. */
  348. static int nonewline = 0;
  349. /* Do not print /etc/issue. */
  350. static int noissue = 0;
  351. /* Do not call vhangup() on the tty. */
  352. static int nohangup = 0;
  353. /* Do not print any hostname. */
  354. static int nohostname = 0;
  355. /* Print the whole string of gethostname() instead of just until the next "." */
  356. static int longhostname = 0;
  357. /* time to wait, seconds */
  358. static int delay = 0;
  359. /* chroot directory */
  360. static char *ch_root = NULL;
  361. /* working directory to change into */
  362. static char *ch_dir = NULL;
  363. /* 'nice' level of the program */
  364. static int priority = 0;
  365. /* automatic login with this user */
  366. static char *autologin = NULL;
  367.  
  368. /* update_utmp() - update our utmp entry */
  369. static void update_utmp (void)
  370. {
  371.     struct utmp ut;
  372.     struct utmp *utp;
  373.     time_t cur_time;
  374.  
  375.     setutent ();
  376.     while ((utp = getutent ()))
  377.         if (utp->ut_type == INIT_PROCESS && utp->ut_pid == pid)
  378.             break;
  379.  
  380.     if (utp) {
  381.         memcpy (&ut, utp, sizeof (ut));
  382.     } else {
  383.         /* some inits don't initialize utmp... */
  384.         const char *x = tty;
  385.         memset (&ut, 0, sizeof (ut));
  386.         if (strncmp (x, "tty", 3) == 0)
  387.             x += 3;
  388.         if (strlen (x) > sizeof (ut.ut_id))
  389.             x += strlen (x) - sizeof (ut.ut_id);
  390.         strncpy (ut.ut_id, x, sizeof (ut.ut_id));
  391.     }
  392.  
  393.     strncpy (ut.ut_user, "LOGIN", sizeof (ut.ut_user));
  394.     strncpy (ut.ut_line, tty, sizeof (ut.ut_line));
  395.     time (&cur_time);
  396.     ut.ut_time = cur_time;
  397.     ut.ut_type = LOGIN_PROCESS;
  398.     ut.ut_pid = pid;
  399.     ut.ut_session = sid;
  400.  
  401.     pututline (&ut);
  402.     endutent ();
  403.  
  404.     updwtmp (_PATH_WTMP, &ut);
  405. }
  406.  
  407. /* open_tty - set up tty as standard { input, output, error } */
  408. static void open_tty (void)
  409. {
  410.     struct sigaction sa, sa_old;
  411.     char buf[40];
  412.     int fd;
  413.  
  414.     //得到要打开的tty终端名
  415.     if (tty[0] == '/')
  416.         strcpy (buf, tty);
  417.     else {
  418.         strcpy (buf, "/dev/");
  419.         strcat (buf, tty);
  420.     }
  421.     
  422.     //修改设备文件属性,使其可以访问
  423.     if (chown (buf, 0, 0) || chmod (buf, 0600))
  424.         if (errno != EROFS)
  425.             error ("%s: %s", tty, strerror (errno));
  426.  
  427.     sa.sa_handler = SIG_IGN;
  428.     sa.sa_flags = 0;
  429.     sigemptyset (&sa.sa_mask);
  430.     sigaction (SIGHUP, &sa, &sa_old);//终端关闭发出SIGHUP信号,忽略此信号
  431.  
  432.     //打开tty终端设备,缺省波特率是115200
  433.     if ((fd = open (buf, O_RDWR, 0)) < 0)
  434.         error ("%s: cannot open tty: %s", tty, strerror (errno));
  435.     if (ioctl (fd, TIOCSCTTY, (void *) 1) == -1)
  436.         error ("%s: no controlling tty: %s", tty, strerror (errno));
  437.     if (!isatty (fd))
  438.         error ("%s: not a tty", tty);
  439.     
  440.     //
  441.     if (nohangup == 0) {
  442.         if (vhangup ())
  443.             error ("%s: vhangup() failed", tty);
  444.         close (2);
  445.         close (1);
  446.         close (0);
  447.         close (fd);
  448.         if ((fd = open (buf, O_RDWR, 0)) != 0)
  449.             error ("%s: cannot open tty: %s", tty,strerror (errno));
  450.         if (ioctl (fd, TIOCSCTTY, (void *) 1) == -1)
  451.             error ("%s: no controlling tty: %s", tty,strerror (errno));
  452.     }
  453.     
  454.     //将标准输入输出出错都复制给tty终端
  455.     if (dup2 (fd, 0) != 0 || dup2 (fd, 1) != 1 || dup2 (fd, 2) != 2)
  456.         error ("%s: dup2(): %s", tty, strerror (errno));
  457.     if (fd > 2)
  458.         close (fd);
  459.  
  460.     if (noclear == 0)
  461.         write (0, "\033c", 2);
  462.     
  463.     //恢复原来SIGHUP的信号处理
  464.     sigaction (SIGHUP, &sa_old, NULL);
  465. }
  466.  
  467. static void output_special_char (unsigned char c)
  468. {
  469.     switch (c) {
  470.     case 's':
  471.         printf ("%s", uts.sysname);
  472.         break;
  473.     case 'n':
  474.         printf ("%s", uts.nodename);
  475.         break;
  476.     case 'r':
  477.         printf ("%s", uts.release);
  478.         break;
  479.     case 'v':
  480.         printf ("%s", uts.version);
  481.         break;
  482.     case 'm':
  483.         printf ("%s", uts.machine);
  484.         break;
  485.     case 'o':
  486.         printf ("%s", uts.domainname);
  487.         break;
  488.     case 'd':
  489.     case 't':
  490.         {
  491.             time_t cur_time;
  492.             struct tm *tm;
  493. #if    0
  494.             char buff[20];
  495.  
  496.             time (&cur_time);
  497.             tm = localtime (&cur_time);
  498.             strftime (buff, sizeof (buff),
  499.                 c == 'd'? "%a %b %d %Y" : "%X", tm);
  500.             fputs (buff, stdout);
  501.             break;
  502. #else
  503.             time (&cur_time);
  504.             tm = localtime (&cur_time);
  505.             if (c == 'd') /* ISO 8601 */
  506.                 printf ("%d-%02d-%02d", 1900 + tm->tm_year,tm->tm_mon + 1, tm->tm_mday);
  507.             else
  508.                 printf ("%02d:%02d:%02d", tm->tm_hour,tm->tm_min, tm->tm_sec);
  509.             break;
  510. #endif
  511.         }
  512.  
  513.     case 'l':
  514.         printf ("%s", tty);
  515.         break;
  516.     case 'u':
  517.     case 'U':
  518.         {
  519.             int users = 0;
  520.             struct utmp *ut;
  521.             setutent ();
  522.             while ((ut = getutent ()))
  523.                 if (ut->ut_type == USER_PROCESS)
  524.                     users++;
  525.             endutent ();
  526.             printf ("%d", users);
  527.             if (c == 'U')
  528.                 printf (" user%s", users == 1 ? "" : "s");
  529.             break;
  530.         }
  531.     default:
  532.         putchar (c);
  533.     }
  534. }
  535.  
  536. static void do_prompt (int showlogin)
  537. {
  538.     FILE *fd;
  539.     int c;
  540.  
  541.     if (nonewline == 0)
  542.         putchar ('\n');
  543.     if (noissue == 0 && (fd = fopen ("/etc/issue", "r"))) {//存有Arago图案,打印此登录图案
  544.         while ((c = getc (fd)) != EOF) {
  545.             if (c == '\\')
  546.                 output_special_char (getc (fd));
  547.             else
  548.                 putchar (c);
  549.         }
  550.         fclose (fd);
  551.     }
  552.     if (nohostname == 0)
  553.         printf ("%s ", hn);
  554.     if (showlogin)
  555.         printf ("login: ");
  556.     fflush (stdout);
  557. }
  558.  
  559. static char *get_logname (void)
  560. {
  561.     static char logname[40];
  562.     char *bp;
  563.     unsigned char c;
  564.  
  565.     tcflush (0, TCIFLUSH);        /* flush pending input */
  566.     for (*logname = 0; *logname == 0;) {
  567.         do_prompt (1);//打印登录图案,argo:
  568.         for (bp = logname;;) {
  569.             if (read (0, &c, 1) < 1) {//从标准输入里读入一个字符
  570.                 if (errno == EINTR || errno == EIO|| errno == ENOENT)
  571.                     exit (EXIT_SUCCESS);
  572.                 error ("%s: read: %s", tty, strerror (errno));
  573.             }
  574.             if (c == '\n' || c == '\r') {//回车或换行符号表示结束
  575.                 *bp = 0;
  576.                 break;
  577.             } else if (!isprint (c))
  578.                 error ("%s: invalid character 0x%x in login"" name", tty, c);
  579.             else if ((size_t)(bp - logname) >= sizeof (logname) - 1)
  580.                 error ("%s: too long login name", tty);
  581.             else
  582.                 *bp++ = c;
  583.         }
  584.     }
  585.     return logname;
  586. }
  587.  
  588. static struct option const long_options[] = {
  589.     { "autologin", required_argument, NULL, 'a' },
  590.     { "chdir", required_argument, NULL, 'w' },
  591.     { "chroot", required_argument, NULL, 'r' },
  592.     { "delay", required_argument, NULL, 'd' },
  593.     { "noclear", no_argument, &noclear, 1 },
  594.     { "nonewline", no_argument, &nonewline, 1 },
  595.     { "noissue", no_argument, &noissue, 1 },
  596.     { "nohangup", no_argument, &nohangup, 1 },
  597.     { "no-hostname", no_argument, &nohostname, 1 }, /* compat option */
  598.     { "nohostname", no_argument, &nohostname, 1 },
  599.     { "loginprog", required_argument, NULL, 'l' },
  600.     { "long-hostname", no_argument, &longhostname, 1 },
  601.     { "nice", required_argument, NULL, 'n' },
  602.     { 0, 0, 0, 0 }
  603. };
  604.  
  605. int main (int argc, char **argv)
  606. {
  607.     char *logname, *s;
  608.     int c;
  609.  
  610.     progname = argv[0];//程序名称,即mingetty
  611.     if (!progname)
  612.         progname = "mingetty";
  613.     /*struct utsname
  614.       { 
  615.          char sysname[_UTSNAME_SYSNAME_LENGTH];//当前操作系统名
  616.          char nodename[_UTSNAME_NODENAME_LENGTH];//网络上的名称
  617.          char release[_UTSNAME_RELEASE_LENGTH];//当前发布级别
  618.          char version[_UTSNAME_VERSION_LENGTH];//当前发布版本
  619.          char machine[_UTSNAME_MACHINE_LENGTH];//当前硬件体系类型
  620.          char domainname[_UTSNAME_DOMAIN_LENGTH]; //当前域名
  621.       };*/
  622.     uname (&uts);//获取当前内核名称和其它信息,并存于utsname结构中
  623.     gethostname (hn, MAXHOSTNAMELEN);//本地主机的标准主机名,存到数组hn中
  624.     hn[MAXHOSTNAMELEN] = '\0';
  625.     pid = getpid ();//取得进程ID
  626.     sid = getsid (0);//get the process group ID of session leader
  627.     putenv ("TERM=linux");//把字符串加到当前环境中,设置的环境仅对程序本身有效
  628.     
  629.     //解析命令行选项参数。
  630.     //字符串optstring可以下列元素:
  631.     //单个字符,表示选项,
  632.     //单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
  633.     //单个字符后跟两个冒号,表示该选项后可以有参数也可以没有参数。如果有参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
  634.     while ((c = getopt_long (argc, argv, "a:d:l:n:w:r:", long_options,(int *) 0)) != EOF) {
  635.         switch (c) {
  636.         case 0:
  637.             break;
  638.         case 'a':
  639.             autologin = optarg;//获得参数-a后面的参数
  640.             break;
  641.         case 'd':
  642.             delay = atoi (optarg);
  643.             break;
  644.         case 'l':
  645.             loginprog = optarg;
  646.             break;
  647.         case 'n':
  648.             priority = atoi (optarg);
  649.             break;
  650.         case 'r':
  651.             ch_root = optarg;
  652.             break;
  653.         case 'w':
  654.             ch_dir = optarg;
  655.             break;
  656.         default:
  657.             usage ();
  658.         }
  659.     }
  660.     
  661.     //s指针保存主机名
  662.     if (longhostname == 0 && (s = strchr (hn, '.')))
  663.         *s = '\0';
  664.         
  665.     //获得终端结构,例如ttyS0等
  666.     tty = argv[optind];
  667.     if (!tty)
  668.         usage ();
  669.         
  670.     //终端名添加"/dev/",变成/dev/ttyS0
  671.     if (strncmp (tty, "/dev/", 5) == 0)
  672.         tty += 5;
  673.  
  674.     update_utmp ();//更新登录信息
  675.     if (delay)
  676.         sleep (delay);
  677.     open_tty ();//打开终端设备
  678.     
  679.     if (autologin) { //如果前边参数为-a且-a后边带有登录名,则会设置autologin即自动登录
  680.         do_prompt (0);//打印登录图形
  681.         printf ("login: %s (automatic login)\n", autologin);
  682.         logname = autologin;//获得自动登录名
  683.     } else//不是自动登录
  684.         while ((logname = get_logname ()) == 0);//获得登录名
  685.     
  686.     if (ch_root)
  687.         chroot (ch_root);
  688.     if (ch_dir)
  689.         chdir (ch_dir);
  690.     if (priority)
  691.         nice (priority);
  692.     
  693.     //带着登录名参数,执行loginprog=/bin/login程序登录,即login--logname
  694.     execl (loginprog, loginprog, autologin? "-f" : "--", logname, NULL);
  695.     /*login函数片段
  696.     。。。。。。。    
  697.     strcpy(buff, "exec ");
  698.     strcat(buff, pwd->pw_shell);
  699.     childArgv[childArgc++] = "/bin/sh";
  700.     childArgv[childArgc++] = "-sh";
  701.     childArgv[childArgc++] = "-c";
  702.     childArgv[childArgc++] = buff;
  703.     childArgv[childArgc++] = NULL;
  704.     //登录成功,执行/bin/sh进入shell
  705.   execvp(childArgv[0], childArgv + 1);
  706.     */
  707.     //启动shell后,首先启动 /etc/profile 文件,然后再启动用户目录下的 ~/.bash_profile、 ~/.bash_login或 ~/.profile文件中的其中一个,执行的顺序为:~/.bash_profile、 ~/.bash_login、 ~/.profile。如果 ~/.bash_profile文件存在的话,一般还会执行 ~/.bashrc文件。
  708.     error ("%s: can't exec %s: %s", tty, loginprog, strerror (errno));
  709.     sleep (5);
  710.     exit (EXIT_FAILURE);
  711. }

猜你喜欢

转载自blog.csdn.net/w892824196/article/details/84492502
今日推荐