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

#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;
}

猜你喜欢

转载自www.cnblogs.com/amwuau/p/9809108.html
今日推荐