使用共享内存将字符串从进程发送到进程
Posted
技术标签:
【中文标题】使用共享内存将字符串从进程发送到进程【英文标题】:send string from process to process using shared memory 【发布时间】:2014-03-27 20:50:04 【问题描述】:我是共享内存的新手,我尝试使用这些代码将字符串从进程发送到另一个进程,当另一个进程接收到字符串时,它将共享内存上的第一个字符设置为“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 ;
【问题讨论】:
在您的函数调用中添加错误检查以查看其中一个是否失败以及原因。 不需要包含sys/shm.h
吗?
【参考方案1】:
我解决了,我包含以下库 --> 和,并将 shmget 函数的最后一个输入更改为 IPC_CREAT |第0666章
【讨论】:
【参考方案2】:看起来在你的 for 循环中,你正在增加你的 's' 变量,所以你实际上并没有将字符串的第一个字符设置为 'a',而是将空终止符设置为 'a'。
尝试改变
*s = 'a';
到
*shm = 'a';
【讨论】:
以上是关于使用共享内存将字符串从进程发送到进程的主要内容,如果未能解决你的问题,请参考以下文章