简体   繁体   中英

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 . 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 | 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'.

Try changing

*s = 'a';

To

*shm = 'a';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM