0

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 ;
        }
2
  • Add error-checking to your function calls to see if one of them fails and why. Commented Mar 27, 2014 at 20:54
  • don't you need to include sys/shm.h? Commented Mar 27, 2014 at 21:08

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.