編輯:關於 Android 開發
坦白說有點慚愧,這個系列一停就是一年半。期間我換到了一家新單位,終於做上了心心念念的嵌入式開發。回頭再看,其實當初的那些執著也沒什麼大不了的。這次我想把「深入淺出 Unix 環境高級編程」這個系列重新拾起來,希望能堅持寫下去。
這兩個概念其實很好理解:程序是存放於磁碟上的可執行檔,而進程則是這個可執行檔載入記憶體、真正跑起來之後的運行態。
打個不太嚴謹但好懂的比方:程序就像一台停在車庫裡的汽車,而進程則是它真正上路行駛時的狀態。
在 Unix 及類 Unix 系統中,每個進程都由一個進程號來標識,它是個非負整數。我們可以寫個簡單的小程式把 PID 印出來:
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- pid = getpid();
- printf("this proccess id is %d\n", pid);
- return 0;
- }
編譯指令為 gcc -o pid pid.c,執行結果如下:
- ./pid
- this proccess id is 24047
- ./pid
- this proccess id is 24048
- ./pid
- this proccess id is 24050
- ./pid
- this proccess id is 24051
- # ./pid
- this proccess id is 24052
可以發現,每次執行的 PID 都不一樣。利用這個特性,我們可以在程式啟動時檢查是否已經有一個相同程式在運行——最常見的做法就是把 PID 寫進一個 .pid 檔裡,作為判斷依據。
於是我把程式改造了一下:
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- char * pidfile = "./freesir.pid";
- pid = getpid();
- int fd = 0;
- char pids[16] = {0};
- if(access(pidfile, F_OK) != -1)
- {
- printf("this program is already run in system.\n");
- return -1;
- }
- fd = open(pidfile, O_TRUNC | O_CREAT | O_RDWR);
- if(fd < 0)
- {
- printf("open pid file error!\n");
- return -2;
- }
- sprintf(pids, "%d", pid);
- if(write(fd, pids, strlen(pids)) != strlen(pids))
- {
- printf("write pid file error!\n");
- return -3;
- }
- sleep(10);
- unlink(pidfile);
- close(fd);
- printf("this proccess id is %d\n", pid);
- return 0;
- }
執行之後,會在當前目錄生成一個 freesir.pid 檔;若在它尚未結束前再次啟動,就會看到「程式已在執行」的提示。原理大致如此。
這裡先對進程控制做個簡單介紹,後面章節會有更詳細的說明。下面的範例分別示範父子進程的建立與等待:
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- int main(int argc, char * argv[])
- {
- pid_t pid = 0;
- int status = 0;
- pid = fork();
- if(pid < 0)
- {
- printf("fork error!\n");
- return 0;
- }
- else if(pid == 0)
- {
- printf("i'm the child proccess. pid = %d\n", getpid());
- sleep(5);
- exit(127);
- }
- else if(pid > 0)
- {
- printf("i'm parent prccess. pid = %d, childpid = %d\n", getpid(), pid);
- }
- pid = waitpid(pid, &status, 0);
- if(pid < 0)
- {
- printf("waitpid error!\n");
- }
- return 0;
- }
這段程式會印出父子進程的 PID。可以觀察到:子進程中 fork 的回傳值為 0,並能用 getpid 取得自己的 PID;父進程則拿到子進程的 PID。最後以 waitpid 等待子進程結束。
需要留意的是,範例中只是簡單地印出訊息,實務上應搭配 waitpid 提供的三個巨集來判斷子進程的結束狀態:
- WIFEXITED(status)
- WEXITSTATUS(status)
- WIFSTOPPED(status)
這些細節留待後續再展開。今天就先聊到這裡,越往下看越覺得 Linux 的設計實在強大,令人折服。
Android 安全專項:AndBug 動態調試工具環境搭建與上手
Android 安全專項:AndBug 動態調試工具環境搭建與上手 AndBug 是一款面向 Android 的動態分析框架,能在不改動 apk 的前提下向目標進程注入腳
NiftyNotification 生動通知效果
NiftyNotification 生動通知效果NiftyNotification 是一個可替代原生 Toast 的開源通知元件,提供多種進場動畫,例如 scale、th
安卓右鍵工具:開發與逆向分析的一站式瑞士軍刀
「安卓右鍵工具」把日常折騰 APK 最常用的十幾件事收攏進右鍵菜單:dex 轉 jar、二進位 XML 查看、APK 信息查詢、圖標提取、zipalign 優化、手機截圖
以 HT for Web 向量繪製 HTML5 檔案上傳進度條
以 HT for Web 向量繪製 HTML5 檔案上傳進度條 在 HTML5 檔案上傳過程中,若沒有進度提示,使用者往往無法判斷上傳狀態。本文以 HT for Web