I need to create a unique name for the file used by the process (running my C ++ program). Before I used the static line, but when I tried to run two instances of the program in parallel, I realized that they both access the same file.
To this end, I would like the file name to include the PID of the process that creates and uses it.
However, when I try to use getpid() , I always get -1 as the return value.
void accessfile(){ std::cout << "DEBUG: accessfile() called by process " << getpid() << " (parent: " << getppid() << ")" << std::endl;
When I run this, I get:
DEBUG: accessfile() called by process -1 (parent: 17565)
I checked ps ux and process 17565 is actually my login shell. How to get the PID of the program that I am currently running?
I noticed this bit of information in manual input 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 the appropriate fork() can cause a problem, but I do not see the behavior that they describe. getppid() correctly gets the parent PID (login shell), but still the return value of getpid() does not make sense.
Can someone shed some light on why it returns -1 (cannot find documentation that details what this return value means), and also how can I get the process id? Do I just need to deploy a dummy process to get the current process id? Thanks!