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 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题