我是新的共享内存,并且我已经尝试了这些代码以将字符串从进程发送到另一个进程,并且当其他进程接收字符串时,它将第一个字符设置为共享内存等于'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 ;
}
将错误检查添加到您的函数调用中,以查看它们中的一个是否失败以及原因。 – zch
你不需要包含'sys/shm.h'吗? – avmohan