1. 程式人生 > >LINUX下C++程式設計如何獲得某程序的ID

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