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

我需要为进程使用的文件(执行我的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?我是否只需要分叉一个虚拟进程来获取当前进程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
}

它说明了为什么使用命名空间std是个坏主意;施工

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...