微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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是个坏主意;施工

原文地址:https://www.jb51.cc/c/119758.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐