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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询