[英]Hey, I wanna send an int array to a client process from the server process using shared memory, I'm not getting the expected output
[英]send string from process to process using shared memory
我是共享内存的新手,我尝试使用这些代码将一个进程中的字符串发送到另一个,当另一个进程接收该字符串时,它将共享内存中的第一个字符设置为等于'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 ;
}
我解决了这个问题,我包括以下库->和,然后将shmget函数的最后一个输入更改为IPC_CREAT | |。 0666
看起来像在for循环中,您正在递增's'变量,因此实际上并不是将字符串的第一个字符设置为'a',而是将空终止符设置为'a'。
尝试改变
*s = 'a';
至
*shm = 'a';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.