2014-03-27 12 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'; 
相关问题