需要当前进程的PID, getpid()返回-1

Need PID of current process, getpid() returns -1

本文关键字:getpid 返回 PID 进程      更新时间:2023-10-16

我需要为进程(执行我的c++程序)使用的文件提供一个唯一的名称。在我使用静态字符串之前,但是当我试图并行运行程序的两个实例时,我意识到它们都在访问同一个文件。

为此,我希望文件名包含创建和使用它的进程的PID。

然而,当我尝试使用getpid()时,我似乎总是得到-1作为返回值。

void accessfile(){
   std::cout << "DEBUG: accessfile() called by process " << getpid() << " (parent: " << getppid() << ")" << std::endl;
   // Code here to create and/or access the file
}

当我运行这个,我得到:

DEBUG: accessfile() called by process -1 (parent: 17565)

我检查了ps ux和进程17565实际上是我的登录shell。我如何得到我正在执行的程序的PID ?

我确实注意到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.

我使用的是glibc 2.4。我理解使用getpid()而没有相应的fork()可能会导致问题,但我没有看到它们描述的行为。getppid()正确地获得父PID(登录shell),但是getpid()的返回值似乎没有意义。

谁能阐明为什么它返回-1(找不到任何详细说明此返回值意味着什么的文档),以及我如何能够获得进程ID?我是否需要只分叉一个虚拟进程来获得当前进程ID?谢谢!

当你在c++中调用系统函数时,显式地使用它们的命名空间(在这种情况下是全局命名空间)是一个好主意:

void accessfile(){
   std::cout << "DEBUG: accessfile() called by process " << ::getpid() << " (parent: " << ::getppid() << ")" << std::endl;
   // Code here to create and/or access the file
}

它显示了为什么使用using namespace std;结构是一个坏主意