我try 打开一个共享内存文件,写入其中,派生到新进程,然后调用execl来运行其他组件,然后在这些组件中访问在父进程中创建的共享内存.但我不想要整个 struct ,只想要其中的一部分.所以我使用offsetof来找到偏移量,并将其传递给mmap.问题是,当我将偏移量更改为非零值时,它会给出无效参数错误.它在零的情况下工作得很好.
我制作了一个带有相同错误的最小伪程序,而较大程序的代码太大. `
#include<stdio.h>
#include<unistd.h>
#include<sys/mman.h>
#include<stddef.h>
#include<fcntl.h>
typedef struct test
{
int moo;
char hello;
}Lil;
typedef struct bigstruct
{
int a;
char cow;
Lil lil;
}Big;
int main()
{
int fd = shm_open("/moomor", O_CREAT | O_RDWR, 0666);
if(fd == -1)
{
perror("shmopen");
return 1;
}
ftruncate(fd, sizeof(Big));
Big * big = (Big *)mmap(NULL, sizeof(Big), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(big == MAP_FAILED)
{
perror("mmap");
return 1;
}
big->lil.hello = 'h';
printf("hello: %c\n", big->lil.hello); //prints correctly
munmap(big, sizeof(Big)); //tried it with this in and out
int offset = offsetof(Big, lil); //gives offset of eight
printf("Offset: %d\n", offset);
Lil *lily = (Lil *)mmap(NULL, sizeof(Lil), PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
if(lily == MAP_FAILED)
{
perror("mmap"); //this causes an error
goto cleanup;
}
printf("HH: %c\n", lily->hello);
munmap(lily, sizeof(Lil));
cleanup:
shm_unlink("/moomor");
close(fd);
}