LINUX下C++编程如何获得某进程的ID

发布网友

我来回答

1个回答

热心网友

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;

pid_t getProcessPidByName(const char *proc_name)
{
     FILE *fp;
     char buf[100];
     char cmd[200] = {'\0'};
     pid_t pid = -1;
     sprintf(cmd, "pidof %s", proc_name);

     if((fp = popen(cmd, "r")) != NULL)
     {
         if(fgets(buf, 255, fp) != NULL)
         {
             pid = atoi(buf);
         }
     }

     printf("pid = %d \n", pid);

     pclose(fp);
     return pid;
}
int main(int argc, char** argv)
{
    if(argc != 2)
    {
        printf("Invalid input! \n");
        return -1;
    }
    char* process_name = argv[1];

    pid_t process_pid = getProcessIDByName((const char*)process_name);

    return 0;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com