Example1:
#include <stdio.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char** argv) {
int fd;
int* p;
int i;
int k;
/* If run with one argument create the shared memory segment
otherwise just connect to it */
if(argc > 1) {
fd = shmget(1234, 5*sizeof(int), IPC_CREAT|0600);
}
else {
fd = shmget(1234, 0, 0);
}
/* Attach to the shared memory segment */
p = shmat(fd, 0, 0);
/* Repeat 20 times */
for(k=0; k<20; k++) {
/* Write the PID on all 5 positions of the shared memory segment.
Add sleep to give the user time for starting other instances */
for(i=0; i<5; i++) {
p[i] = getpid();
sleep(1);
}
/* Print the content of the shared memory segment. It will most
likely contain a mix of PIDs belonging to all the instances of this program */
printf("%d: ", getpid());
for(i=0; i<5; i++) {
printf("%5d ", p[i]);
}
printf("\n");
}
/* Detach from the shared memory segment */
shmdt(p);
/* If run with one argument, then it created the shared memory
segment, so now it must destory it */
if(argc > 1) {
shmctl(fd, IPC_RMID, NULL);
}
return 0;
}
Example 2 (server/client):
First run server, then client. Commands useful: ipcs -m (to see the create memory location) ; ipcrm -M 9876 (to delete it)
Server.c----------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/shm.h>
#include<sys/ipc.h>
#define SMSIZE 100
int main(){
int shmid;
key_t key;
char *shm;
char *s;
key=9876;
shmid=shmget(key, SMSIZE, IPC_CREAT | 0666);
if (shmid<0){
perror("shmget");
exit(1);
}
shm=shmat(shmid, NULL, 0);
if (shm==(char *) -1){
perror("shmat");
exit(1);
}
memcpy(shm, "Hello world", 11);
s=shm;
s+=11;
*s=0;
while (*shm != '*')
sleep(1);
return 0;
}
Client.c----------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/shm.h>
#include<sys/ipc.h>
#define SMSIZE 100
int main(){
int shmid;
key_t key;
char *shm;
char *s;
key=9876;
shmid=shmget(key, SMSIZE, 0666);
if (shmid<0){
perror("shmget");
exit(1);
}
shm=shmat(shmid, NULL, 0);
if (shm==(char *) -1){
perror("shmat");
exit(1);
}
for (s=shm; *s!=0; s++ ){
printf("%c", *s);
}
printf("\n");
*shm='*';
return 0;
}
Other examples: https://users.cs.cf.ac.uk/Dave.Marshall/C/node27.html