【发布时间】: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。所以可能ftruncate。mmap可能会返回MAP_FAILED。fork也可以返回-1。您必须检查错误情况并采取相应措施(例如打印来自errno的错误代码,例如使用perror并退出)。
标签: c operating-system printf shared-memory asprintf