2012-04-21 172 views
1

我想用共享內存來保存由兩個父子進程打印的字符。子進程將'a','b','c','d'保存到前四個字節中,然後父進程將'A','B','C','D'保存到接下來的四個字節。但它不會work.the代碼如下:父進程和子進程共享一個IPC共享內存

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/shm.h> 

int 
main(int argc, char **argv) { 
     int shmid,i,j,off_a,off_b; 
     char *ptr; 
     pid_t pid; 

     shmid = shmget(IPC_PRIVATE, 200, SHM_W | SHM_R | IPC_CREAT); 
     if (shmid < 0) { 
       printf("cannot create shared memory\n");exit(-1); 
     } 
     if ((ptr = shmat(shmid, NULL, 0)) == (void *)-1) { 
       printf("cannot attach shared memory to address\n"); 
       exit(-1); 
     } 

     if ((pid = fork()) < 0) { 
       printf("fork error\n");exit(-1); 
     } else if (pid) { 

       wait(); 

       for (i = 'A', off_a = 0; i <= 'D'; i++ ,off_a += 1) 
         sprintf(ptr + off_a,"%c",i); 

       printf("RESULT:%s \n", ptr); 

     } else { 
       for (j = 'a', off_b = 4; j <= 'd'; j++, off_b += 1) 
         sprintf(ptr + off_b,"%c",j); 

       exit(0); 

     } 
} 

我認爲結果是abcdABCD,但是當我運行它,它打印ABCD,我用gdb調試它,並將其寫入到文件中, 'a'字符丟失。爲什麼會發生?

0000000 A B C D \0 b c d \0 \0 \0 \0 \0 \0 \0 \0 
0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 
* 
+0

原因是,當你訪問c中的一個字符串時,字符串由最終的NULL(\ 0)分隔,這樣函數就能夠判斷字符串的結束位置。 – byrondrossos 2012-04-21 15:42:55

回答

0

sprintf增加了一個尾隨NULL;

更換

sprintf(ptr + off_a,"%c",i); 

*(ptr + off_a) = i; 

,同樣與其他的sprintf。

+0

謝謝。所以這是問題。 – 2012-04-21 15:57:58

相關問題