0

How can get I get the PID of the "firefox" process in C?

In this code, system only returns 0, indicating success. How can I get the PID?

int x = system("pidof -s firefox");
printf("%d\n", x);
user253751
  • 50,383
  • 6
  • 45
  • 81
robo
  • 115
  • 9

1 Answers1

1

popen is what you want: it opens a process and output from the open process is available to read just like a file stream opened with fopen:

FILE *f = popen("pgrep firefox", "r");
if (NULL == f)
{
    perror("popen");
}
else
{   
    char buffer[128];
    while (fgets(buffer, sizeof buffer, f))
    {
         // do something with read line
         int pid;
         sscanf(buffer, "%d", &pid)
    }
    // close the process
    pclose(f);
}

See man popen

David C. Rankin
  • 75,900
  • 6
  • 54
  • 79
Mathieu
  • 7,837
  • 6
  • 30
  • 43