Need PID of current process, getpid() returns -1
When you call system functions in C++ it is a good idea to explicitly use their namespace (global one in this case):
void accessfile(){
std::cout << "DEBUG: accessfile() called by process " << ::getpid() << " (parent: " << ::getppid() << ")" << std::endl;
// Code here to create and/or access the file
}
And it shows why it is a bad idea to use using namespace std;
construction
tomocafe
Updated on July 16, 2022Comments
-
tomocafe almost 2 years
I need to come up with a unique name for a file used by a process (executing my C++ program). Before I used a static string, but when I tried to run two instances of the program in parallel, I realized they were both accessing the same file.
To this end, I would like the file name to include the PID of the process that creates and is using it.
However, when I try to use
getpid()
, I always seem to get-1
as the return value.void accessfile(){ std::cout << "DEBUG: accessfile() called by process " << getpid() << " (parent: " << getppid() << ")" << std::endl; // Code here to create and/or access the file }
When I run this, I get:
DEBUG: accessfile() called by process -1 (parent: 17565)
I checked
ps ux
and the process17565
is actually my login shell. How do I get the PID of the program I'm currently executing?I did notice this bit of information in the manual entry for
getpid()
:Since glibc version 2.3.4, the glibc wrapper function for getpid() caches PIDs, so as to avoid additional system calls when a process calls getpid() repeatedly. Normally this caching is invisible, but its correct operation relies on support in the wrapper functions for fork(2), vfork(2), and clone(2): if an application bypasses the glibc wrappers for these system calls by using syscall(2), then a call to getpid() in the child will return the wrong value (to be precise: it will return the PID of the parent process). See also clone(2) for discussion of a case where getpid() may return the wrong value even when invoking clone(2) via the glibc wrapper function.
Indeed I am using glibc 2.4. I understand that using
getpid()
without a correspondingfork()
may cause an issue, but I don't see the behavior they describe.getppid()
correctly gets the parent PID (the login shell), but yet the return value ofgetpid()
doesn't seem to make sense.Can anyone shed light on why it returns -1 (can't find any documentation that details what this return value means), and also how I might be able to get the process ID? Do I need to just fork a dummy process just to get the current process ID? Thanks!