zhl410 2017-04-30 14:26 采纳率: 0%
浏览 1918

使用共享内存的方式实现进程间通信,读取数据时报“总线错误”。感觉有点意思

**
#include // exit()
#include //fork()
#include // pid_t
#include // wait()
#include // printf()
#include
#include
#include
#include // shm_open(), ftruncate(), mmap(), shm_unlink()
#include
int main(int argc, char* argv[]){

const int SIZE = 4096;
const char *name = "OS";
static int count = 0;
if(argc !=2 ){
    perror("usage error");
    exit(-1);
}
int num = atoi(argv[1]);

int shm_fd;
void *ptr;
shm_fd = shm_open(name, O_CREAT, 0666);
ftruncate(shm_fd, SIZE);

if( num > 0)
{
    pid_t pid;
    pid = fork();
    if(pid == 0)
    {
        int shm_fd;
        void *ptr;
        shm_fd = shm_open(name, O_RDWR, 0666);
        ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

        sprintf(ptr, "%d", num);
        ptr += sizeof(int);
        count ++;

        while(num != 1)
        {
            num = (num%2 == 0 ? num/2 : 3*num+1);
            sprintf(ptr, "%d", num);
            ptr += sizeof(int);
            count++;
        }
    }
    else if(pid >0)
    {
        wait(NULL);

        int shm_fd;
        void *ptr;
        shm_fd = shm_open(name, O_RDONLY, 0666);
        ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
        int *p = (int*) ptr;
        printf("%d ", *p++);
        while(count > 0){
            printf("%d ",*p++);
            count --;
        }

        shm_unlink(name);
        printf("\n");
    }
    else
    {
        perror("fork error");
        exit(-1);
    }   
}
else
{
    perror("please input a positive interge");
    exit(-1);
}   

return 0;

}
**

  • 写回答

2条回答 默认 最新

  • devmiao 2017-04-30 15:29
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作