试图写一个int在共享内存中(使用mmap)有一个子进程 [英] Trying to write to an int in shared memory (using mmap) with a child process
问题描述
我与一些code,需要家长和派生的子进程之间的通信玩耍。我创建了一个叉前共享内存int,但我似乎做与孩子过程中的任何变化不会当父进程访问的影响INT。这里是一片code的,说明我的问题。
I'm playing around with some code that requires communication between a parent and a forked child process. I've created an int in shared memory before the fork, but any changes I make with the child process don't seem to affect the int when accessed by the parent process. Here's a piece of code that illustrates my problem.
int * shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
pid_t child;
int childstate;
if((child=fork())==0){
*shared = 1;
exit(0);
}
waitpid (child, &childstate, 0);
printf("%d",*shared);
虽然子进程设置的共享为1的值,这个程序输出0。
Although the child process sets the value of 'shared' to 1, this program outputs 0.
在我实际的程序结构将被共享,而不是一个int,但如果我能想出这个code片段,我觉得剩下的应该水到渠成。
In my actual program a struct will be shared instead of an int, but if I can figure out this code snippet, I think the rest should fall into place.
我决不是一个有经验的程序员,我有点陌生C.我花了几个小时试图弄清楚这一点,并宣读几十这不能不说应该是一个简单的过程页面。说实话,它一直是一个沉重的打击,我的自尊:)。我敢肯定,我只是缺少一些小细节 - 有谁能够指出来给我吗?在此先感谢您的时间。
I'm by no means an experienced programmer, and I'm a bit unfamiliar with C. I've spent hours trying to figure this out and read dozens of pages which say it should be a simple process. To be honest, it's been a heavy blow to my self esteem :) . I'm sure I'm just missing some small detail - can anybody point it out to me? Thanks in advance for your time.
推荐答案
您的问题是传递到标志的mmap()
,你希望 MAP_SHARED
。
Your problem is the flags passed into mmap()
, you want MAP_SHARED
.
int * shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
作品与code低于预期。
Works as expected with the code below
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
int main(void) {
int * shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
pid_t child;
int childstate;
printf("%d\n", *shared);
if((child=fork())==0){
*shared = 1;
printf("%d\n", *shared);
exit(0);
}
waitpid (child, &childstate, 0);
printf("%d\n",*shared);
}
输出:
0
1
1
的mmap手册页可以帮助你,如果你还没有发现它。
mmap man page may help you if you haven't already found it.
这篇关于试图写一个int在共享内存中(使用mmap)有一个子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!