【发布时间】:2014-02-04 15:27:39
【问题描述】:
我在 Linux 上编译它:g++ test.c -o test
我重写了原来的例子。 现在让第一个进程等待 2 秒,(以便 process2 可以在共享内存上写入),然后我让 process1 从该内存中读取。这个测试正确吗?
第二个问题:我应该放在哪里:
shmdt(tests[0]); // or 1
shmctl(statesid, IPC_RMID, 0);
//Global scope
char *state[2];
//...
//...
struct teststruct {
int stateid;
teststruct *next;
//other things
};
void write(teststruct &t, char* what)
{
strcpy(state[t.next->stateid], what);
printf("\n\nI am (%d), I wrote on: %d", t.stateid, t.next->stateid);
}
void read(teststruct &t)
{
printf("\n\nI am (%d), I read: **%s**", t.stateid, state[t.stateid]);
}
int main() {
key_t key;
if ((key = ftok(".", 'a')) == -1) {
perror("ftok");
exit(1);
}
int statesid;
if ((statesid = shmget(key, sizeof(char*)*50, 0600 | IPC_CREAT )) == -1) {
perror("shmget error");
exit(1);
}
state[0] = (char*)shmat(statesid, NULL, 0);
state[1] = (char*)shmat(statesid, NULL, 0);
teststruct tests[2];
tests[0].stateid = 0;
tests[0].next = &tests[1];
tests[1].stateid = 1;
tests[1].next = &tests[0];
int t0, t1;
switch (t0 = fork()) {
case (0):
sleep(2);
read(tests[0]);
exit(0);
case (-1):
printf("\nError!");
exit(-1);
default:
wait();
}
switch (t1 = fork()) {
case (0):
write(tests[1], "1 write on 0 in theory.");
exit(0);
case (-1):
printf("\nError!");
exit(-1);
default:
wait();
}
return 0;
}
我特别问的是“状态”是否真的在两个进程之间共享,以及我所做的是否是这样做的好方法。
我的目标是在 fork 之后让 char *state[2] 在两个进程之间共享(读取/修改)。
【问题讨论】:
-
我建议你先写一段非常简单的代码,然后用它来好好感受一下共享内存的含义。现在这个程序充满了陷阱,只能在偶然的情况下工作(因为分叉的进程通常继承相同的虚拟映射,但不能保证在另一个操作系统上仍然可以工作)。
-
好的,谢谢。我只需要它作为“锻炼”目的在 Linux 上工作。
标签: c++ c fork shared-memory