LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   PID of a running process in C++ (https://www.linuxquestions.org/questions/linux-software-2/pid-of-a-running-process-in-c-4175580658/)

jegadezz 05-25-2016 08:54 AM

PID of a running process in C++
 
I am writing a code and I want to set CPU affinity of a process for which I need its PID . How can I read the pid of running processes in C++ code.

Any help is appreciable.

hazel 05-25-2016 10:47 AM

There's a C-library getpid() function that returns the PID of the current process. You can use getppid() to get the PID of the parent.

jegadezz 05-25-2016 12:09 PM

Hi Hazel , thanks for your reply . Actually I am looking for another independent process's id whose I know only the name . Its neither the child or parent process of my program.

HMW 05-25-2016 12:59 PM

How about something like this?
Code:

#include <stdio.h>
#include <stdlib.h>
#define LEN 10

int main()
{
        char line[LEN];
        FILE *cmd = popen("pidof -s cbatticon", "r");
        long pid = 0;

        fgets(line, LEN, cmd);
        pid = strtoul(line, NULL, 10);
       
        printf("%ld\n", pid);
       
        pclose(cmd);
       
        return 0;
}

My output:
Code:

$ ./myPidof
365

My output from terminal:
Code:

pidof -s cbatticon
365
ps aux | grep cbatti | grep -v grep
HMW    365  0.0  1.1  63368 24276 tty1    Sl  18:51  0:02 cbatticon

Probably bug prone as hell, no expert at C (read: amateur!), mostly stolen from here:
http://stackoverflow.com/questions/8...x-in-c#8166467

Best regards,
HMW

sundialsvcs 05-25-2016 03:12 PM

Bear in mind, also, that "CPU affinity" is customarily set by rules, or heuristics, which do not presume prior knowledge of a particular PID. The exceptions are low-level system calls which presume that the PID is already known, e.g. by its parent.


All times are GMT -5. The time now is 06:04 AM.