我有一个应用程序,我需要编写一个新的 getpid 函数来替换原始操作系统。实现类似于:
pid_t getpid(void)
{
if (gi_PID != -1)
{
return gi_PID;
}
else
{
// OS level getpid() function
}
}
如何通过该函数调用操作系统原始的 getpid() 实现?
编辑:我尝试过:
pid_t getpid(void)
{
if (gi_PID != -1)
{
return gi_PID;
}
else
{
return _getpid();
}
}
正如乔纳森所建议的那样。当使用 g++ 编译时,这给了我以下错误:
In function
pid_t getpid()': SerendibPlugin.cpp:882: error:
_getpid' undeclared (first use this function) SerendibPlugin.cpp:882: error: (Each undeclared identifier is reported only once for each function it appears in.)
编辑2:我已经成功地通过使用函数指针并使用 dlsym(RTLD_NEXT, "getpid") 将其设置为 id“getpid”的下一秒符号来使其工作。
这是我的示例代码:
vi xx.c
"xx.c" 23 lines, 425 characters
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <dlfcn.h>
using namespace std;
pid_t(*___getpid)();
pid_t getpid(void)
{
cout << "My getpid" << endl;
cout << "PID :" << (*___getpid)() << endl;
return (*___getpid)();
}
int main(void)
{
___getpid = (pid_t(*)())dlsym(RTLD_NEXT, "getpid");
pid_t p1 = getpid();
printf("%d \n", (int)p1);
return(0);
}
g++ xx.c -o xout
My getpid
PID :7802
7802
最佳答案
在许多系统上,您会发现 getpid()
是 _getpid()
的“弱符号”,可以调用它来代替 getpid ()
.
第一个版本的答案提到__getpid()
;由于它是错误的,该提及很快被删除。
此代码适用于 Solaris 10 (SPARC) - 使用 C++ 编译器:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
extern "C" pid_t _getpid();
pid_t getpid(void)
{
return(-1);
}
int main(void)
{
pid_t p1 = getpid();
pid_t p2 = _getpid();
printf("%d vs %d\n", (int)p1, (int)p2);
return(0);
}
此代码适用于 Solaris 10 (SPARC) - 使用 C 编译器:
Black JL: cat xx.c
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
pid_t getpid(void)
{
return(-1);
}
int main(void)
{
pid_t p1 = getpid();
pid_t p2 = _getpid();
printf("%d vs %d\n", (int)p1, (int)p2);
return(0);
}
Black JL: make xx && ./xx
cc xx.c -o xx
"xx.c", line 13: warning: implicit function declaration: _getpid
-1 vs 29808
Black JL:
关于c++ - 用我自己的实现替换 getpid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/796106/