2017-09-11 4 views
-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; 
} 
+0

당신이 오류를 확인합니까 :

$ 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에 의해, 그것이 있어야 가리키는 정수를 인쇄 할 가정? – spectras

+0

코드를 확인하는 데 오류가 없습니다. 입력이 항상 정확하다고 가정 할 수 있습니다. –

+1

누구를 말합니까? 사용하는 모든 단일 통화가 실패 할 수 있습니다. shm_open은'-1'을 반환 할 수 있습니다. 그래서'ftruncate' 할 수 있습니다. 'mmap'은'MAP_FAILED'를 리턴 할 수 있습니다. 'fork'도'-1'을 반환 할 수 있습니다. ** 오류 조건을 확인하고 그에 따라 행동해야합니다 (예를 들어,'perror' (https://linux.die.net/man/3/perror)를 사용하여'errno'에서 오류 코드를 출력하십시오) 끝내라.). – spectras

답변

1

귀하의 컴파일러를 들어보세요! 어떤 시점에서

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

그게 시작이지만 게시 된 샘플에는 여러 가지가 잘못되었습니다. 무효 포인터 연산? 잘못된 시스템 호출 인수? 오류 검사 부족? 문자열 표현에 대한 오해? 코드를 실행하지 않고도 빠르게 살펴볼 수 있습니다. – spectras

+0

@spectras 예, 코드에는 많은 문제가 있지만 원시 포인터 값을 인쇄하는 즉시 문제를 해결할 것입니다. – Tim