LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   [C++] How to fetch the process id of the currently active C++ file? (https://www.linuxquestions.org/questions/linux-newbie-8/%5Bc-%5D-how-to-fetch-the-process-id-of-the-currently-active-c-file-4175449630/)

Aquarius_Girl 02-11-2013 04:35 AM

[C++] How to fetch the process id of the currently active C++ file?
 
I tried this:

Code:

#include <iostream>
#include <stdlib.h>
#include <sstream>

int main ()
{
    std::stringstream psOutput;
    psOutput << "ps --no-headers -f -p " << getpid();

    system (psOutput.str().c_str());

    return 0;
}

The output:
Code:

anisha@linux-trra:~/> ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
anisha    6426  6423  0 13:32 pts/0    00:00:00 /bin/bash
anisha    7590  6426  0 15:32 pts/0    00:00:12 kwrite api.cpp
anisha    8099  6426  0 16:02 pts/0    00:00:00 ps -f

anisha@linux-trra:~/> g++ api.cpp -Wall
anisha@linux-trra:~/> ./a.out
anisha    8119  6426  0 16:03 pts/0    00:00:00 ./a.out

anisha@linux-trra:~/>

I wanted the pid of api.cpp, not of a.out.

How to solve this?

pan64 02-11-2013 04:40 AM

a cpp files is not runnable, it is not a process. It will be compiled, and linked together with other compiled files and the result will be one single program. if you execute this process it will get a process id. In a multithreaded environment all the running threads will get also an id, but a source file (like your cpp) will never have a process id.

Aquarius_Girl 02-11-2013 04:41 AM

Quote:

Originally Posted by pan64 (Post 4888953)
but a source file (like your cpp) will never have a process id.

Thanks! What I was seeing was actually the pid of kwrite, not
of that cpp file!

I actually wanted to fetch the file name and was thinking of
extracting it from output of ps! :doh:

The simpler way is __FILE__! :)
http://gcc.gnu.org/onlinedocs/cpp/St...ed-Macros.html


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