2014-03-27 14 views
0

我是新的共享內存,並且我已經嘗試了這些代碼以將字符串從進程發送到另一個進程,並且當其他進程接收字符串時,它將第一個字符設置爲共享內存等於'a'字符。但是當我要運行其中的一個,我得到分段錯誤消息:使用共享內存發送字符串從進程到進程

 #include <stdlib.h> 
     #include<stdio.h> 
     #include <string.h> 
     int main(int argc , char *argv[]) 
     { 
      key_t key = 111 ; 
      int id = shmget(key , 512 , 1 | 0666); 
      char *s = shmat(id , 0 , 0) ; 
      strcpy(s,argv[1]) ; 
      while(*s == 'a') sleep(1) ; 
      return 0 ; 
     } 
    // and this is the code for reciever >  
     #include <stdlib.h> 
     #include<stdio.h> 
     int main(int argc , char *argv[]) 
     { 
      key_t key = 111 ; 
      int id = shmget(key , 512 , 1 | 0666); 
      char* shm = shmat(id , 0 , 0) ; 
      char *s = shm ; 
      for(s = shm; *s != NULL ; s++) 
       putchar(*s) ; 
      *s = 'a' ; 
      return 0 ; 
     } 
+0

將錯誤檢查添加到您的函數調用中,以查看它們中的一個是否失敗以及原因。 – zch

+0

你不需要包含'sys/shm.h'嗎? – avmohan

回答

1

我解決這個問題,我有以下庫 - >和,並改變shmget的功能可按最後輸入IPC_CREAT | 0666

0

它看起來就像在你的循環,你增加你的'變量,這樣你就不會實際設置的第一個字符你的字符串爲'a',而是'a'的空終止符。

嘗試改變

*s = 'a'; 

*shm = 'a'; 
相關問題