이 코드의 목표는 공유 메모리 공간을 생성하고 자식에 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;
}
당신이 오류를 확인합니까 :
당신이
ptr
에 의해, 그것이 있어야 가리키는 정수를 인쇄 할 가정? – spectras코드를 확인하는 데 오류가 없습니다. 입력이 항상 정확하다고 가정 할 수 있습니다. –
누구를 말합니까? 사용하는 모든 단일 통화가 실패 할 수 있습니다. shm_open은'-1'을 반환 할 수 있습니다. 그래서'ftruncate' 할 수 있습니다. 'mmap'은'MAP_FAILED'를 리턴 할 수 있습니다. 'fork'도'-1'을 반환 할 수 있습니다. ** 오류 조건을 확인하고 그에 따라 행동해야합니다 (예를 들어,'perror' (https://linux.die.net/man/3/perror)를 사용하여'errno'에서 오류 코드를 출력하십시오) 끝내라.). – spectras