1. 程式人生 > >linux shell 獲取程序id,或者在應用程式中獲取程序id

linux shell 獲取程序id,或者在應用程式中獲取程序id

1、linux shell下獲取程序ID的方法:

  1.  ps -A |grep "/usr/sbin/gps_app"| awk '{if($6 == "'start'") {print $1}}'
  2.  pidof "cmdname"
  3.  pgrep "cmdname"

這三種在bash和busybox ash裡面的執行結果稍有不同,

第一種:ps -A,列出所有程序

grep "cmdname",過濾得到匹配cmdname欄位的程序

awk '{if($6 == "'start'") {print $1}}',匹配到第6列為start欄位的那一行,打印出該行的第一列

第二種: pidof 只能獲取程式的檔名匹配到的程序號,在ash中 比如 pidof "usr/bin/telnetd" 和 pidof "telnetd"中結果不一樣, 前一種結果為空,但是在bash中執行兩者一樣。

第三種: pgrep方法 pidof "usr/bin/ser_app" 和 pidof "ser_app"執行結果相同,都是返回匹配到的程序id。

2、c語言獲取程序id

int gps_pid = getpid();

sprintf(sys_cmd, "echo %d >/var/run/gps_app.pid", gps_pid);

system(cmd);