I have a problem when I run my code. My shmat fails and prints permission denied. I searched on google how to solve it but I can't. My code is the following:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define ERROR -1
int main ( int argc, char *argv[] ) {
int shmid,key=50;
int *val;
int *x;
int rw = -1;
// 0 for write and 1 for read
shmid = shmget ( key, sizeof( int ), IPC_CREAT );
if ( shmid == -1 ) {
perror ( "Error in shmget\n" );
return ( ERROR );
}
val = ( int * ) shmat ( shmid, NULL, 0 );
if ( val == -1 ) {
perror ( "Error in shmat\n" );
return ( ERROR );
}
scanf ( "%d", &rw);
while ( rw >= 0 ) {
if ( rw == 0 ) {
//write in the shared memory
x = ( int * ) malloc ( sizeof ( int ) );
if ( x == NULL ) {
perror ( "Error in malloc" );
return ( ERROR );
}
scanf ( "%d", x );
val = x;
}
else {
// read from the shared memory
if ( rw == 1 ) {
printf ( "%d\n", *val );
}
}
scanf ( "%d", &rw );
}
return ( 0 );
}
In this code I want to test the shared memory. I write an integer in the shared memory when I give rw = 1 else I read the value of the shared memory and then I print this value. I can't find where is the problem....