2010-11-20 46 views
2

我在我的笔记本下面的代码写的,我现在把它写在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警告:传递“等待”的参数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; 
} 

任何人都可以解释为什么这是怎么回事?

+0

你应该经常检查返回值。使用IPC时,'ipcs(1)'命令很有帮助(它应该没有显示共享内存段的权限)。 – ninjalj 2010-11-20 12:06:47

+0

你好在哪里把ipcs(1)放在代码中? – 2010-11-20 13:34:47

回答

2

0777/IPC_CREAT应该是0777|IPC_CREAT(逻辑或,而不是除法)。

+0

好的!我一直在看这5分钟,甚至没有考虑它=) – BeemerGuy 2010-11-20 10:45:34

+0

@ Bobj-C;这是你的手写!!!!! =) – BeemerGuy 2010-11-20 10:46:35

+0

好的谢谢你的答案,但Xcode输出开始于父母写:0,1为什么不孩子睡眠(1);应该得到孩子,并执行printf或... – 2010-11-20 10:50:07

0

对于wait的问题,请参阅man waitpid