【问题标题】:error bad execution (operating system course) need explainerror bad execution(操作系统课程)需要解释
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 不错的收获!我一直在看这个 5 分钟,甚至没有考虑它 =)
  • 好的,感谢您的回答,但是 xcode 输出以 Parent write:0,1 为什么不让 sleep(1) 开始;应该找到孩子并执行 printf 或...
  • 由于他们都睡了 1 秒,你不能完全确定哪个会先执行,但父母是一个不错的选择。如果您想尝试让孩子先走,请更改睡眠时间。此外,您可以通过将该行更改为 waitpid(pid, NULL, 0); 来修复编译警告。但它不应该影响输出。
【解决方案2】:

有关wait 的问题,请参阅man waitpid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2019-04-07
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多