[英]send string from process to process using shared memory
I'm new with shared memory , and i have tried these codes to send a string from process to another , and when the other process recives the string , it set the first character on the shared memory equal to 'a' character . 我是共享内存的新手,我尝试使用这些代码将一个进程中的字符串发送到另一个,当另一个进程接收该字符串时,它将共享内存中的第一个字符设置为等于'a'字符。 but when i want to run one of them , i get segmentation fault message : 但是,当我想运行其中之一时,出现分段错误消息:
#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 ;
}
I solve it , i include the following libraries --> and , and change the last input of shmget funciton to IPC_CREAT | 我解决了这个问题,我包括以下库->和,然后将shmget函数的最后一个输入更改为IPC_CREAT | |。 0666 0666
It looks like in your for loop, you are incrementing your 's' variable, so you are not actually setting the first character of your string to 'a', but rather the null-terminator to 'a'. 看起来像在for循环中,您正在递增's'变量,因此实际上并不是将字符串的第一个字符设置为'a',而是将空终止符设置为'a'。
Try changing 尝试改变
*s = 'a';
To 至
*shm = 'a';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.