此代码的目标是创建共享内存空间并在子级中为其写入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;
}
答案 0 :(得分: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));