我有3段代码:main.c、main2.c和sharedlib.c
Main.c:
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
extern char* sharedPtr;
int main(void)
{
sharedPtr = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
fprintf(stdout, "addr = 0x%x\n", sharedPtr);
sleep(10);
munmap(sharedPtr, 1024);
return 0;
}
Main2.c:
#include <stdio.h>
extern char* sharedPtr;
int main(void)
{
fprintf(stdout, "0x%x\n", (void*)sharedPtr);
return 0;
}
sharedlib. c(只包含一个指针,没有其他内容):
char* sharedPtr;
当我启动Main时,它会打印出来,然后Hibernate 10秒:
addr = 0xb6f77000
在这10秒内,我启动了main2,但得到以下输出:
0x0
为什么?Main.c仍然在运行,所以它应该已经在共享库中设置了变量,但是它没有.为什么main2看不到指针的值?
我是如何编译的:
gcc main.c -o main -L${PWD} -lsharedlib
gcc main2.c -o main2 -L${PWD} -lsharedlib
gcc sharedlib.c -o libsharedlib.so -shared -fPIC
EDIT:将该指针替换为随机整数,您将得到完全相同的结果,即main2看不到值main写入其中.Main2只打印0.换句话说,它与mmap的使用无关.