android的init執行個體

來源:互聯網
上載者:User

標籤:init   android   

      這段時間沒事,主要是主管太垃圾,沒有合理的安排下屬,導致我很閑,剛好,我利用這段時間可以好好學習下android。

        今天看了android的init這部分,我自己想能不能自己寫個守護進程在andorid啟動後就運行起來,這樣可以更深刻瞭解android的init的相關知識,只是看書印象不深刻。

         總結了下,大致分成兩步完成:

         1)編寫守護進程相關code,寫Android.mk,編譯android code,產生守護進程的可執行檔。

         2)修改init.rc的相關內容,在init.rc中調用守護進程。

第一步:

       守護進程準備寫個隔60s記錄寫檔案的進程,這個code主要從網上其它地方copy過來的,因為這裡主要是想說明init中如何調用可執行檔,對代碼不是很關心。

/*

* init_daemon.cpp

*/

#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

void init_daemon(void)
{
   int pid;
   int i;
   if(pid=fork())
       exit(0);        //是父進程,結束父進程
   else if(pid< 0)
       exit(1);        //fork失敗,退出
   //是第一子進程,後台繼續執行
   setsid();           //第一子進程成為新的交談群組長和進程組長
   //並與控制終端分離
   if(pid=fork())
       exit(0);        //是第一子進程,結束第一子進程
   else if(pid< 0)
       exit(1);        //fork失敗,退出
   //是第二子進程,繼續
   //第二子進程不再是交談群組長
   for(i=0;i< NOFILE;++i)  //關閉開啟的檔案描述符
       close(i);

   chdir("/");      //改變工作目錄到/
   umask(0);           //重設檔案建立掩模
   return;
}


/*

* mark_log.cpp

*/

#include <stdio.h>
#include <time.h>

void init_daemon(void);//守護進程初始化函數

int main(int nargs,char *args)
{
   FILE *fp;
   time_t t;
   init_daemon();//初始化為Daemon

   while(1)//每隔一分鐘向test.log報告運行狀態
   {
       sleep(60);//睡眠一分鐘
       if((fp=fopen("/test.log","a")) >=0){
           t=time(0);
           fprintf(fp,"Im here at %sn",asctime(localtime(&t)) );
           fclose(fp);
       }
   }
   return 0;
}


/*

* Android.mk

*/

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \
init_deamon.cpp \
mark_log.cpp

LOCAL_MODULE:= marklog

include $(BUILD_EXECUTABLE)

上述三個檔案都放在framework檔案夾下的marklog檔案夾下(marklog是建立的檔案夾)。


第二步:修改init.rc

在init.rc的最後添加

service marklog /system/bin/marklog
   class core
   disabled
   oneshot

表示marklog為一個service,然後在適當地方啟動這個service,我是在on post-fs-data section中添加

“start marklog”

當然修改init.rc的方法很多,不是僅限於上面。


然後編譯android,產生kernel和rootfs,重新燒kernel和rootfs,android起來了ps -ef就可以看到有marklog進程,並且每隔一分鐘會在test.log中記錄資訊。




本文出自 “肉肉之家” 部落格,請務必保留此出處http://4895268.blog.51cto.com/4885268/1410903

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.