Created
April 28, 2023 13:00
-
-
Save fherbine/21660f4571ccebddc21b56ecc11cbd12 to your computer and use it in GitHub Desktop.
IPC shared memory Proof Of Concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* HOW TO USE ? | |
* | |
* 1. Compile the program using `gcc shm_sysV.c` | |
* 2. Start the master process by typing `./a.out "Any string of your choice"` | |
* 3. Finally, you can visualize the shared buffer of memory by starting another process | |
* without any arguments: `./a.out`. | |
* 4. When you're done you can kill the master process and free the memory (Ctrl+C) | |
* | |
*/ | |
// General purpose includes | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <signal.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
// SHM includes | |
#include <sys/types.h> | |
#include <sys/ipc.h> | |
#include <sys/shm.h> | |
#define PROJ_ID 1 | |
#define KEY_PATH "./key.lock" | |
#define SIZE 64 | |
static volatile char keep_running = 1; | |
void keyboard_interrupt(int dummy) | |
{ | |
keep_running = 0; | |
} | |
void master(char *str, int shmid) { | |
char *buffer; | |
signal(SIGINT, keyboard_interrupt); | |
if ((buffer = shmat(shmid, NULL, 0)) == -1) { | |
printf("Cannot attach memory :%s\n", strerror(errno)); | |
exit(-1); | |
} | |
strcpy(buffer, str); | |
while (keep_running) {;} | |
if (shmdt(buffer) == -1) { | |
perror("shmdt"); | |
exit(1); | |
} | |
if (shmctl(shmid, IPC_RMID, 0) == -1) { | |
perror("shmctl"); | |
exit(1); | |
} | |
} | |
void slave(int shmid) { | |
char *buffer; | |
if ((buffer = shmat(shmid, NULL, SHM_RDONLY)) == -1) { | |
printf("Cannot attach memory :%s\n", strerror(errno)); | |
exit(-1); | |
} | |
printf("Read: %s\n", buffer); | |
if (shmdt(buffer) == -1) { | |
perror("shmdt"); | |
exit(1); | |
} | |
} | |
int main(int argc, char **argv) { | |
key_t ipc_key; | |
int shmid; | |
char *segment; | |
if ((ipc_key = ftok(KEY_PATH, PROJ_ID)) == -1) | |
{ | |
printf("cannot acquire key :%s\n", strerror(errno)); | |
exit(-1); | |
} | |
if ((shmid = shmget(ipc_key, SIZE, IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP )) == -1) | |
{ | |
printf("Cannot create/get Semaphore: %s\n", strerror(errno)); | |
exit(-1); | |
} | |
printf("Get shm, id: %d\n", shmid); | |
if (argc < 2) | |
slave(shmid); | |
else | |
master(argv[1], shmid); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment