需要当前进程的PID, getpid()返回-1
Need PID of current process, getpid() returns -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。我理解使用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;
结构是一个坏主意
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 为什么if(fork()==0){getpid()}和popen()进程返回相同的进程id
- 需要当前进程的PID, getpid()返回-1