简体   繁体   English

exec后两个进程之间的共享内存

[英]Shared Memory between two processes after exec

Parent:家长:

shm_id = shmget(IPC_PRIVATE, (1 << 16), IPC_CREAT | IPC_EXCL | 0777);
setenv("SOME_ENV_VAR",stringof(shm_id);
if(fork()=0){
    execve(some_path,argv);
}

Child:孩子:

int shm_id = atoi(getenv("SOME_ENV_VAR"));
int *shared_mem = (int*)shmat(shm_id,0,NULL);
if(!shared_mem)
  return;
shared_mem[0]++;

I want to edit the shared memory in the child.我想编辑孩子的共享记忆。 Any reasons why this should not work?这不应该起作用的任何原因? I am allocating the shared mem block via shmget in the Parent.Im placing the shm_id as an env variable for the child to read it after the fork and exec.我正在通过 Parent.Im 中的 shmget 分配共享内存块。我将 shm_id 作为 env 变量,让孩子在 fork 和 exec 之后读取它。

In the child, I am reading the proper shm_id then trying to get a pointer to the shared memory via shmat.在孩子中,我正在读取正确的 shm_id,然后尝试通过 shmat 获取指向共享内存的指针。 In my code I have verified the shm_id in Parent and Child are the same... Any ideas?在我的代码中,我已经验证了 Parent 和 Child 中的 shm_id 是相同的......有什么想法吗?

The key_t argument to shmget is not the same as the identifier that that function returns. shmgetkey_t参数与该函数返回的标识符不同。 It's not sensible to substitute one for the other.用一种代替另一种是不明智的。

However, if you change that and communicate the shmid instead of the key , your basic approach will work.但是,如果您更改它并传达shmid而不是key ,您的基本方法将起作用。

The shmid is a system-wide global identifier, and shmat will succeed if you have the appropriate process permissions, even if you are an unrelated process. shmid是一个系统范围的全局标识符,如果您具有适当的进程权限,即使您是一个不相关的进程, shmat也会成功。 (And, even if you are related, an execve will detach any shared memory segments, requiring an explicit re-attach.) (而且,即使你是相关的, execve也会分离任何共享内存段,需要显式重新附加。)

Note that the spec is not terribly explicit about this, saying that "[e]ach individual shared memory segment ... shall be identified by a unique positive integer, called ... a shared memory identifier, shmid ."请注意,规范对此并没有非常明确,说“[e]每个单独的共享内存段......应由一个唯一的正整数标识,称为......共享内存标识符, shmid 。” . .

On OS level segments are identified by the key , the ID is local to a process only.在 OS 级别段由key标识, ID仅对进程本地。 Each process needs to do a get (passing them same key) and an at to use the memory.每个进程都需要执行get (向它们传递相同的密钥)和at以使用内存。

An example here: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html这里的一个例子: http : //www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM