Three files, one header file, one read and one Write File, apply for shared memory with the same key value.
// SHM. h
# Ifndef _ shm_com_h
# DEFINE _ shm_com_h 1
# Define text_sz 2048
Struct shared_use_at
{
Int written_by_you;
Char some_text [text_sz];
};
Struct KTs
{
Int power;
Int mode;
Int temp;
Int windspeed;
Int write_flag;
};
# Endif
// Shm_write.c
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/SHM. h>
# Include "SHM. H"
Int main ()
{
Int running = 1;
Void * shared_memory = (void *) 0;
Struct shared_use_at * shared_stuff;
Char buffer [bufsiz];
Int shmid;
Shmid = shmget (key_t) 1234, sizeof (struct shared_use_at), 0666 | ipc_creat );
If (shmid =-1)
{
Fprintf (stderr, "shmget failed/N ");
Exit (exit_failure );
}
Shared_memory = shmat (shmid, (void *) 0, 0 );
If (shared_memory = (void *)-1)
{
Fprintf (stderr, "shmat failed/N ");
Exit (exit_failure );
}
Printf ("memory attached at % x/N", (INT) shared_memory );
Shared_stuff = (struct shared_use_at *) shared_memory;
While (running)
{
While (shared_stuff-> written_by_you = 1)
{
Sleep (1 );
Printf ("waiting for client.../N ");
}
Printf ("Enter some text :");
Fgets (buffer, bufsiz, stdin );
Strncpy (shared_stuff-> some_text, buffer, text_sz );
Shared_stuff-> written_by_you = 1;
If (strncmp (buffer, "end", 3) = 0)
{
Running = 0;
}
}
If (shmdt (shared_memory) =-1)
{
Fprintf (stderr, "shmdt failed/N ");
Exit (exit_failure );
}
Exit (exit_success );
}
// Shm_read.c
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/SHM. h>
# Include "SHM. H"
Int main ()
{
Int running = 1;
Void * shared_memory = (void *) 0;
Struct shared_use_at * shared_stuff;
Int shmid;
Srand (unsigned INT) getpid ());
Shmid = shmget (key_t) 1234, sizeof (struct shared_use_at), 0666 | ipc_creat );
If (shmid =-1)
{
Fprintf (stderr, "shmget failed/N ");
Exit (exit_failure );
}
Shared_memory = shmat (shmid, (void *) 0, 0 );
If (shared_memory = (void *)-1)
{
Fprintf (stderr, "shmat failed/N ");
Exit (exit_failure );
}
Printf ("memory attached at % x/N", (INT) shared_memory );
Shared_stuff = (struct shared_use_at *) shared_memory;
Shared_stuff-> written_by_you = 0;
While (running)
{
If (shared_stuff-> written_by_you)
{
Printf ("You wrote: % s", shared_stuff-> some_text );
Sleep (RAND () % 4 );
Shared_stuff-> written_by_you = 0;
If (strncmp (shared_stuff-> some_text, "end", 3) = 0)
{
Running = 0;
}
}
}
If (shmdt (shared_memory) =-1)
{
Fprintf (stderr, "shmdt failed/N ");
Exit (exit_failure );
}
If (shmctl (shmid, ipc_rmid, 0) =-1)
{
Fprintf (stderr, "shmctl (ipc_rmid) failed/N ");
Exit (exit_failure );
}
Exit (exit_success );