【发布时间】:2010-11-20 10:36:50
【问题描述】:
我在noteBook中写了下面的代码,现在我在xcode中写了,这是老师的输出:
child reads : 0,1
parent write: 1,2
child reads : 1,2
parent write: 3,5
child reads : 3,5
parent write: 8,13
child reads : 8,13
由于这 2 个错误,我无法获得输出:
1-节目接收信号:“EXC_BAD_ACCESS”。并标记线a[0]
2-警告:传递 'wait' 的参数 1 使指针从整数而不进行强制转换
代码:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/wait.h>
int main (int argc, const char * argv[]) {
int shmid ,*a,*b,i;
shmid = shmget(IPC_PRIVATE, 2*sizeof(int), 0777/IPC_CREAT);
int pid = fork();
if (pid == 0) {
b=(int *)shmat(shmid, 0, 0);
for(i = 0; i < 10;i++){
sleep(1);
printf("child reads: %d,%d\n",b[0],b[1]);
}
}
else {
a= (int *)shmat(shmid, 0, 0);
a[0] = 0; //after compile this line marked in red
a[1] = 1;
for(i = 0; i <10;i++){
sleep(1);
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
printf("Parent write:%d,%d\n",a[0],a[1]);
}
wait(pid);//warning message above
}
return 0;
}
谁能解释为什么会这样?
【问题讨论】:
-
您应该始终检查返回值。使用 IPC 时,
ipcs(1)命令很有帮助(它应该在您的共享内存段上显示没有权限)。 -
你好 ipcs(1) 放在代码的什么地方?
标签: c linux operating-system pid