【问题标题】:Issue writing and reading from shared memory space c从共享内存空间 c 发出写入和读取
【发布时间】:2017-09-11 22:44:20
【问题描述】:

此代码的目标是创建一个共享内存空间并将 n 的值写入子进程中,然后打印从父进程中生成的所有数字。但这目前只是打印出像 16481443B4 这样的内存地址,每次我运行程序时都会改变。我不确定我是错误地写入共享内存还是错误地读取共享内存。可能两者兼而有之。

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/mman.h>

int main(int argc, char** argv){

    //shared memory file descriptor
    int shm_fd;

    //pointer to shared memory obj
    void *ptr;
    //name of shared obj space
    const char* name = "COLLATZ";

    //size of the space
    const int SIZE = 4096;

    //create a shared memory obj
    shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);

    //config size
    ftruncate(shm_fd, SIZE);

    //memory map the shared memory obj
    ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

    int n = atoi(argv[1]);
    pid_t id = fork();

    if(id == 0) {
        while(n>1) {
            sprintf(ptr, "%d",n);
            ptr += sizeof(n);
            if (n % 2 == 0) {
                n = n/2;
            } else {
                n = 3 * n + 1;
            }
        }
        sprintf(ptr,"%d",n);
        ptr += sizeof(n);
    } else {
        wait(NULL);
        printf("%d\n",(int*)ptr);
    }

    //Umap the obj
    munmap(ptr, SIZE);

    //close shared memory space
    close(shm_fd);

    return 0;
}

【问题讨论】:

  • 什么时候检查错误?
  • 我没有任何错误检查代码我可以假设输入总是正确的
  • 谁说的?您使用的每个呼叫都可能失败。 shm_open 可能会返回 -1。所以可能ftruncatemmap 可能会返回 MAP_FAILEDfork 也可以返回 -1。您必须检查错误情况并采取相应措施(例如打印来自errno 的错误代码,例如使用perror 并退出)。

标签: c operating-system printf shared-memory asprintf


【解决方案1】:

听听你的编译器!

$ gcc main.c -lrt
main.c: In function 'main':
main.c:51:9: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
  printf("%d\n",(int*)ptr);
         ^

假设要打印ptr指向的整数,应该是:

printf("%d\n",*((int*)ptr));

【讨论】:

  • 这是一个开始,但是发布的示例中有很多错误。空指针算术?不正确的系统调用参数?缺乏错误检查?对字符串表示的误解?无需尝试运行代码即可快速浏览。
  • @spectras 是的,代码有很多问题,但这将解决打印出原始指针值的直接问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2018-10-16
  • 2015-01-19
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多