rafaelmaeuer
1/1/2020 - 9:36 PM

get PID from name - C (get linux process ID by name)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int GetPIDbyName(char* pidName)
{
    FILE *fp;
    char pidofCmd[50]={0};
    int pidValue=-1;
        
    if(pidName != 0) {
        strcpy(pidofCmd, "pidof ");
        strcat(pidofCmd, pidName);
        strcat(pidofCmd,  "> /tmp/pidof");
        system(pidofCmd); 
        fp = fopen("/tmp/pidof", "r");
        fscanf(fp, "%d", &pidValue);
        fclose(fp);
    }
    return pidValue;
}

int main() 
{
      int eclipsePid = GetPIDbyName("eclipse") ; 
      if(eclipsePid < 0) {
          printf("error on get eclipse pid\n");
      } else {
          printf("eclipse pid: %d\n", eclipsePid);
      }
      return 0;
}