我在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
由于这两个错误,我无法获得输出:
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;
}
谁能解释为什么会这样?