-1

此代码的目标是创建一个共享内存空间并将 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;
}
4

1 回答 1

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));
于 2017-09-11T23:17:37.737 回答