Chinaunix首页 | 论坛 | 博客
  • 博客访问: 94760
  • 博文数量: 24
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 171
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-24 12:12
个人简介

好好学习天天向上

文章分类

全部博文(24)

文章存档

2018年(1)

2016年(7)

2015年(6)

2014年(10)

我的朋友

分类: Android平台

2015-12-23 21:19:22

之所以研究init.rc文件,是想在andriod系统起来之后init自动运行system/bin/目录下面的一个程序,然后在这个程序挂掉的时候自动把它拉起来,这样就能保证这个程序能够一直在内存中运行。

假设需要运行的程序为/system/bin/hellodemo,那么需要在init.rc中创建一个service,内容如下

  1. service hello_demo /system/bin/hellodemo
  2.     class late_start
  3.     user system
  4.     group system net_admin inet net_raw shell misc adb log input


    枚红色的字体为关键字,service要顶格写,下面的options: class user group要空四个空格之后再开始写。class的意思就是给service分一个类,同一类的service必须要同时start和stop,默认的class为default,写不同的class能让hello_demo程序起来的先后顺序会不同。usergroup是控制hello_demo程序的用户ID和组ID,不同的用户ID和组ID会有不同的权限,group可设置多个参数。如果权限没有设对,android在启动过程中会出现各种奇怪的问题。service的options除了上面三个,还有其他两个比较常用的:disabled在程序不需要自动启动时使用和oneshot是在程序exit之后不需要重新启动。
 
   在hellodemo中open了/dev/mtgpio这个设备,所以需要修改/dev/mtgpio的权限,在init.rc文件的 on boot 关键字的下面添加如下内容:

  1. on boot
  2.     ...
  3.     ...
  4.     chmod 777 /dev/ttyMT0
  5.     chown system system /dev/ttyMT0
  6.     chmod 777 /dev/mtgpio

    
    on是一个action的关键字,boot是一个触发器(trigger),表示满足了这个条件下面的各条命令(command)就会被执行,chmod修改文件权限,chown修改用户ID(UID)和组ID(GID)

    在hellodemo需要将数据保存在/data/local/中的txt文件中,所以需要在init.rc中创建一个可读可写的目录,在init.rc文件的on post-fs-data关键字下添加如下内容:

  1. on post-fs-data
  2.     ...
  3.     ...
  4.     mkdir /data/local 0751 root root
  5.     mkdir /data/local/tmp 0777 system system

此处的mkdir命令参数和shell中运行的命令不同,切不可直接复制到shell中运行(我比较傻,犯了这个错误,在shell中要用mkdir -m 777 /data/local/tmpchown system:system /data/local/tmp两条命令实现),此外,此两条创建目录的command如果放到init.rc的on boot关键字下面,将会无效,具体原因还没整明白,望高手指教。
    
    在init.rc文件中对应的地方增加了上面的三段配置后,/system/bin/hellodemo就能在系统启动的时候自动运行,且down掉的时候能够被init重新拉起来。

如果是程序自己运行挂掉了,结果如下:
root@teft6735_65c_l1:/ #
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     12016  680   ffffffff 81ffd034 S /system/bin/hellodemo
root@teft6735_65c_l1:/ #
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     10992  712   ffffffff 81ffd030 t /system/bin/hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     10992  712   ffffffff 81ffd030 t /system/bin/hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     10992  712   ffffffff 81ffd030 t /system/bin/hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     0      0     000a1420 00000000 Z hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     0      0     000a1420 00000000 Z hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     0      0     000a1420 00000000 Z hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    767   1     0      0     000a1420 00000000 Z hellodemo
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    4346  1     12016  684   ffffffff abf73034 S /system/bin/hellodemo
root@teft6735_65c_l1:/ #
注意红色字体的进程号和进程状态的变化。

如果hellodemo是被kill掉的,运行结果如下:
root@teft6735_65c_l1:/ #
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    4346  1     12016  684   ffffffff abf73034 S /system/bin/hellodemo
root@teft6735_65c_l1:/ #
root@teft6735_65c_l1:/ # kill -9 4346
kill -9 4346
root@teft6735_65c_l1:/ # ps |grep "hello"
ps |grep "hello"
system    4925  1     12016  684   ffffffff a5bc7034 S /system/bin/hellodemo
root@teft6735_65c_l1:/ #

    最详细的最靠谱的描述工程中init.rc文件内容格式的文件为system/core/init/readme.txt,此文件内容如下readme.txt

 

Android Init Language

---------------------

 

The Android Init Language consists of four broad classes of statements,

which are Actions, Commands, Services, and Options.

init.rc文件包含Actions, Commands, Services, and Options.四个部分)

 

All of these are line-oriented, consisting of tokens separated by

whitespace.  The c-style backslash escapes may be used to insert

whitespace into a token.  Double quotes may also be used to prevent

whitespace from breaking text into multiple tokens.  The backslash,

when it is the last character on a line, may be used for line-folding.

(以行为顺序执行,关键字用空格间隔,反斜杠(backslash)在一行结尾的时候表示续行符)

 

Lines which start with a # (leading whitespace allowed) are comments.

(以#开始的一行表示注释(允许以空格开头)

 

Actions and Services implicitly declare a new section.  All commands

or options belong to the section most recently declared.  Commands

or options before the first section are ignored.

ActionsServices隐含声明了一个新的段,所有的commandsoptions属于最近的一个声明的段,在第一个段之前的commandsoptions都被忽略)
换个简单的说法就是:老大Actions(其实就 on关键字)后面有一群小弟command,另外一个老大Services(其实就是service关键字)后面有一群小弟option,一个老大后面 带一群小弟组成一个完整的帮派,小弟单独冲在所有老大的前面,结果就是gameover(挂了,尘埃,空气,屁...)

Actions and Services have unique names.  If a second Action or Service

is declared with the same name as an existing one, it is ignored as

an error.  (??? should we override instead)

 

 

Actions

-------

Actions are named sequences of commands.  Actions have a trigger which

is used to determine when the action should occur.  When an event

occurs which matches an action's trigger, that action is added to

the tail of a to-be-executed queue (unless it is already on the

queue).

 

Each action in the queue is dequeued in sequence and each command in

that action is executed in sequence.  Init handles other activities

(device creation/destruction, property setting, process restarting)

"between" the execution of the commands in activities.

 

Actions take the form of:

 

on <trigger>

   <command>

   <command>

   <command>

 

 

Services

--------

Services are programs which init launches and (optionally) restarts

when they exit.  Services take the form of:

 

service <name> <pathname> [ <argument> ]*

   <option>

   <option>

   ...

 

 

Options

-------

Options are modifiers to services.  They affect how and when init

runs the service.

 

critical

   This is a device-critical service. If it exits more than four times in

   four minutes, the device will reboot into recovery mode.

 

disabled

   This service will not automatically start with its class.

   It must be explicitly started by name.

 

setenv <name> <value>

   Set the environment variable <name> to <value> in the launched process.

 

socket <name> <type> <perm> [ <user> [ <group> [ <context> ] ] ]

   Create a unix domain socket named /dev/socket/<name> and pass

   its fd to the launched process.  <type> must be "dgram", "stream" or "seqpacket".

   User and group default to 0.

   Context is the SELinux security context for the socket.

   It defaults to the service security context, as specified by seclabel or

   computed based on the service executable file security context.

 

user <username>

   Change to username before exec'ing this service.

   Currently defaults to root.  (??? probably should default to nobody)

   Currently, if your process requires linux capabilities then you cannot use

   this command. You must instead request the capabilities in-process while

   still root, and then drop to your desired uid.

 

group <groupname> [ <groupname> ]*

   Change to groupname before exec'ing this service.  Additional

   groupnames beyond the (required) first one are used to set the

   supplemental groups of the process (via setgroups()).

   Currently defaults to root.  (??? probably should default to nobody)

 

seclabel <securitycontext>

  Change to securitycontext before exec'ing this service.

  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.

  Services on the system partition can instead use policy-defined transitions

  based on their file security context.

  If not specified and no transition is defined in policy, defaults to the init context.

 

oneshot

   Do not restart the service when it exits.

 

class <name>

   Specify a class name for the service.  All services in a

   named class may be started or stopped together.  A service

   is in the class "default" if one is not specified via the

   class option.

 

onrestart

    Execute a Command (see below) when service restarts.

 

Triggers

--------

   Triggers are strings which can be used to match certain kinds

   of events and used to cause an action to occur.

 

boot

   This is the first trigger that will occur when init starts

   (after /init.conf is loaded)

 

<name>=<value>

   Triggers of this form occur when the property <name> is set

   to the specific value <value>.

 

device-added-<path>

device-removed-<path>

   Triggers of these forms occur when a device node is added

   or removed.

 

service-exited-<name>

   Triggers of this form occur when the specified service exits.

 

 

Commands

--------

 

exec <path> [ <argument> ]*

   Fork and execute a program (<path>).  This will block until

   the program completes execution.  It is best to avoid exec

   as unlike the builtin commands, it runs the risk of getting

   init "stuck". (??? maybe there should be a timeout?)

 

export <name> <value>

   Set the environment variable <name> equal to <value> in the

   global environment (which will be inherited by all processes

   started after this command is executed)

 

ifup <interface>

   Bring the network interface <interface> online.

 

import <filename>

   Parse an init config file, extending the current configuration.

 

hostname <name>

   Set the host name.

 

chdir <directory>

   Change working directory.

 

chmod <octal-mode> <path>

   Change file access permissions.

 

chown <owner> <group> <path>

   Change file owner and group.

 

chroot <directory>

  Change process root directory.

 

class_start <serviceclass>

   Start all services of the specified class if they are

   not already running.

 

class_stop <serviceclass>

   Stop all services of the specified class if they are

   currently running.

 

domainname <name>

   Set the domain name.

 

enable <servicename>

   Turns a disabled service into an enabled one as if the service did not

   specify disabled.

   If the service is supposed to be running, it will be started now.

   Typically used when the bootloader sets a variable that indicates a specific

   service should be started when needed. E.g.

     on property:ro.boot.myfancyhardware=1

        enable my_fancy_service_for_my_fancy_hardware

 

 

insmod <path>

   Install the module at <path>

 

mkdir <path> [mode] [owner] [group]

   Create a directory at <path>, optionally with the given mode, owner, and

   group. If not provided, the directory is created with permissions 755 and

   owned by the root user and root group.

 

mount <type> <device> <dir> [ <mountoption> ]*

   Attempt to mount the named device at the directory <dir>

   <device> may be of the form mtd@name to specify a mtd block

   device by name.

   <mountoption>s include "ro", "rw", "remount", "noatime", ...

 

restorecon <path> [ <path> ]*

   Restore the file named by <path> to the security context specified

   in the file_contexts configuration.

   Not required for directories created by the init.rc as these are

   automatically labeled correctly by init.

 

restorecon_recursive <path> [ <path> ]*

   Recursively restore the directory tree named by <path> to the

   security contexts specified in the file_contexts configuration.

   Do NOT use this with paths leading to shell-writable or app-writable

   directories, e.g. /data/local/tmp, /data/data or any prefix thereof.

 

setcon <securitycontext>

   Set the current process security context to the specified string.

   This is typically only used from early-init to set the init context

   before any other process is started.

 

setenforce 0|1

   Set the SELinux system-wide enforcing status.

   0 is permissive (i.e. log but do not deny), 1 is enforcing.

 

setkey

   TBD

 

setprop <name> <value>

   Set system property <name> to <value>.

 

setrlimit <resource> <cur> <max>

   Set the rlimit for a resource.

 

setsebool <name> <value>

   Set SELinux boolean <name> to <value>.

   <value> may be 1|true|on or 0|false|off

 

start <service>

   Start a service running if it is not already running.

 

stop <service>

   Stop a service from running if it is currently running.

 

symlink <target> <path>

   Create a symbolic link at <path> with the value <target>

 

sysclktz <mins_west_of_gmt>

   Set the system clock base (0 if system clock ticks in GMT)

 

trigger <event>

   Trigger an event.  Used to queue an action from another

   action.

 

wait <path> [ <timeout> ]

  Poll for the existence of the given file and return when found,

  or the timeout has been reached. If timeout is not specified it

  currently defaults to five seconds.

 

write <path> <string>

   Open the file at <path> and write a string to it with write(2)

   without appending.

 

 

Properties

----------

Init updates some system properties to provide some insight into

what it's doing:

 

init.action

   Equal to the name of the action currently being executed or "" if none

 

init.command

   Equal to the command being executed or "" if none.

 

init.svc.<name>

   State of a named service ("stopped", "running", "restarting")

 

 

Example init.conf

-----------------

 

# not complete -- just providing some examples of usage

#

on boot

   export PATH /sbin:/system/sbin:/system/bin

   export LD_LIBRARY_PATH /system/lib

 

   mkdir /dev

   mkdir /proc

   mkdir /sys

 

   mount tmpfs tmpfs /dev

   mkdir /dev/pts

   mkdir /dev/socket

   mount devpts devpts /dev/pts

   mount proc proc /proc

   mount sysfs sysfs /sys

 

   write /proc/cpu/alignment 4

 

   ifup lo

 

   hostname localhost

   domainname localhost

 

   mount yaffs2 mtd@system /system

   mount yaffs2 mtd@userdata /data

 

   import /system/etc/init.conf

 

   class_start default

 

service adbd /sbin/adbd

   user adb

   group adb

 

service usbd /system/bin/usbd -r

   user usbd

   group usbd

   socket usbd 666

 

service zygote /system/bin/app_process -Xzygote /system/bin --zygote

   socket zygote 666

 

service runtime /system/bin/runtime

   user system

   group system

 

on device-added-/dev/compass

   start akmd

 

on device-removed-/dev/compass

   stop akmd

 

service akmd /sbin/akmd

   disabled

   user akmd

   group akmd

 

Debugging notes

---------------

By default, programs executed by init will drop stdout and stderr into

/dev/null. To help with debugging, you can execute your program via the

Andoird program logwrapper. This will redirect stdout/stderr into the

Android logging system (accessed via logcat).

(默认情况下,被init执行的程序,stdoutstderr都被输出到/dev/null里面去了,所以,在程序运行过程中用logcat是没有办法抓到printf输出的log的。知道了这个原因,就不会因为一句log都没有打印出来纠结伤神了。)

 

For example

service akmd /system/bin/logwrapper /sbin/akmd

以上内容为作者学习心得,如有错误欢迎指正。


阅读(11363) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~