Pergunta

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 ;
        }
Foi útil?

Solução

I solve it , i include the following libraries --> and , and change the last input of shmget funciton to IPC_CREAT | 0666

Outras dicas

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';
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top