linux擷取進程id和進程名稱

來源:互聯網
上載者:User


linux擷取進程id和進程名稱 作為一個共用庫,應該需要統計使用本庫的各種應用程式的使用頻率,使用方法等資訊。才能針對主要應用做出更好的改進。  www.2cto.com  那麼就需要記錄調用者的進程id或者進程名稱,並且儲存下來。儲存的動作可以採用共用記憶體,也可以採用檔案,這個在下篇博文描述,本文描述如何擷取進程id和進程名稱。範例: #include <stdio.h>#include <unistd.h> #define CFGMNG_TASK_NAME_LEN 256 int main(){    int ret;    char ac_tmp[CFGMNG_TASK_NAME_LEN];  ret = cfgmng_get_taskname(ac_tmp, CFGMNG_TASK_NAME_LEN);  if (0 != ret) {      printf("Call cfgmng_get_taskname fail.\n");      return -1;  }  printf("The running task name is %s.\n", ac_tmp);  return 0;}  int cfgmng_get_taskname(char *ac, int len){    int count = 0;    int nIndex = 0;    char chPath[CFGMNG_TASK_NAME_LEN] = {0};    char cParam[100] = {0};    char *cTem = chPath;    int tmp_len;     pid_t pId = getpid();    sprintf(cParam,"/proc/%d/exe",pId);/*    printf("cParam = %s.\n", cParam);*/    count = readlink(cParam, chPath, CFGMNG_TASK_NAME_LEN);/*    printf("count = %d.\n", count);*/    if (count < 0 || count >= CFGMNG_TASK_NAME_LEN)    {        printf("Current System Not Surport Proc.\n");        return -1;    }    else    {        nIndex = count - 1;         for( ; nIndex >= 0; nIndex--)        {            if( chPath[nIndex] == '/' )//篩選出進程名            {                nIndex++;                cTem += nIndex;                break;             }        }    }    tmp_len = strlen(cTem);    if (0 == tmp_len) {        printf("Get task fail.\n");        return -1;    }        if (len <= tmp_len +1) {        printf("len(%d) is less than taskname(%s)'s len.\n", len, cTem);        return -1;    }        strcpy(ac, cTem);        return 0;}從上面的實驗範例可以看出,主要使用的函數是getpid擷取本進程的id,再到/proc/pid/exe
中去找到對應的進程名稱。在/proc目錄中有很多跟進程相關的東西,都可以用這種方法觸類旁通地實現。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.