進程名字獲取進程的進程號PID,類似pidof,C函數,適合linux,AIX和hp-unix平臺

之前寫過一篇文章,linux下根據進程名字獲取進程號,但是隻能在linux下使用,這次更新一版,適合linux,AIX和hp-unix平臺。

其實原理很簡單,就是利用了ps命令,前段時間更新blog比較慢,工作忙....其實工作忙都是藉口......

/***************************************************************************
* File name    :        findpidbyname.c
* Function     :        like pidof
* Author       :        [email protected]
* Date         :        2013/08/
* Version      :             v1.0
* Description  :           Find process's pid by name in linux\aix\hp-ux
* ModifyRecord :
****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#define MAXBUFLEN 1024
#define HP_ENV "UNIX_STD"


int find_pid_by_name( char* ProcName, int* foundpid)
{
        char c_result[MAXBUFLEN], c_command[MAXBUFLEN];
        int i;
        FILE *fp;
/*
 * 在hp-unix環境下,需要在編譯時加上-DHP
 *
 */

#ifdef HP
        int rv;
        rv = setenv(HP_ENV, "2003", 1);
        if(rv != 0)
        {
                printf("In HP-Unix environment, set env UNIX_STD failed! Can't find pid of %s", ProcName);
                return -1;
        }
#endif
        snprintf(c_command, sizeof(c_command), "ps -eo pid,comm | grep -w %s | awk '{print $1}'", ProcName);

        fp = popen(c_command, "r");
        if(fp == NULL)
        {
#ifdef HP
                unsetenv(HP_ENV);
#endif
                printf("popen failed, errno is %d.\n", errno);
                return -1;
        }

        i = 0;
        while(fgets(c_result, sizeof(c_result), fp) != NULL)
        {
                foundpid[i++] = atoi(c_result);
        }

        foundpid[i] = 0;

        pclose(fp);

#ifdef HP
        unsetenv(HP_ENV);
#endif
        return 0;


}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章