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
  • 57,427
  • 7
  • 48
  • 90
robo
  • 115
  • 10

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
  • 81,885
  • 6
  • 58
  • 85
Mathieu
  • 8,840
  • 7
  • 32
  • 45