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

标签 c++ linux unix process

我需要为进程(执行我的 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。我知道在没有相应的 fork() 的情况下使用 getpid() 可能会导致问题,但我没有看到他们描述的行为。 getppid() 正确获取父 PID(登录 shell),但 getpid() 的返回值似乎没有意义。

谁能阐明它返回 -1 的原因(找不到任何详细说明此返回值含义的文档),以及我如何获得进程 ID?我是否只需要 fork 一个虚拟进程just 来获取当前进程 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; 构造是个坏主意

关于c++ - 需要当前进程的 PID,getpid() 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537538/

相关文章:

linux - 混合hadoop集群

linux - Bash 脚本检查远程运行命令的权限

linux - 脚本中的别名

c - 通过 libpcap 写一个类似 squid 的程序

c++ - 是否可以使用比较器函数过滤掉 STL multiset lower_bound 检查的数据?

c - 从辅助线程获取主线程

c++ - 多个 OpenGL 纹理在某些情况下不起作用?

c++ - 将类作为函数参数传递

c++ - boost find in shared-memory方法卡在c++多进程项目中

c++ - Visual Studio 在白色窗口而不是控制台中运行 C++