简体   繁体   English

使用共享内存从一个进程到另一个进程发送字符串

[英]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.

相关问题 嘿,我想使用共享 memory 从服务器进程向客户端进程发送一个 int 数组,我没有得到预期的 output - 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 使用共享内存从单独的C进程访问numpy数组 - Access numpy array from separate C process using shared memory 使用共享内存时子进程挂起? - Child process hangs when using shared memory? 通过不同的过程更新共享内存 - Updating shared memory by different process 有没有办法在不使用共享内存的情况下从另一个进程更改进程的数据? - Is there any way to change the data of a process from another one without using shared memory? 尝试使用子进程写入共享内存中的int(使用mmap) - Trying to write to an int in shared memory (using mmap) with a child process 如何使用共享内存创建新进程并与之通信 - How to create a new process and communicate with that using shared memory 使用共享内存(mmap)和信号量进行进程间通信 - inter process communication using shared memory(mmap) and semaphores 每个客户端服务器使用C中的共享内存一个进程 - One Process per Client Server using Shared Memory in C 使用共享内存将数据结构传递给另一个进程并保存到文件 - Passing data structure to another process using shared memory and saving to file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM