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