Skip to content

Instantly share code, notes, and snippets.

@senior-sigan
Last active November 16, 2022 14:21
Show Gist options
  • Save senior-sigan/42807193576edc8789dc9215cbfd78be to your computer and use it in GitHub Desktop.
Save senior-sigan/42807193576edc8789dc9215cbfd78be to your computer and use it in GitHub Desktop.
Shared memory demo
CC = clang
CFLAGS = -pedantic -pedantic-errors -Wall -Werror -Wextra
LDFLAGS =
.PHONY: all
all: build_sender build_receiver
./sender /shmem1
./receiver /shmem1
.PHONY: build_sender
build_sender:
$(CC) $(CFLAGS) $(LDFLAGS) sender.c -o sender
.PHONY: build_receiver
build_receiver:
$(CC) $(CFLAGS) $(LDFLAGS) receiver.c -o receiver
.PHONY: reformat
reformat:
clang-format -i --style=Google receiver.c sender.c
#include <fcntl.h> /* for O_* consts */
#include <stdio.h> /* print */
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <sys/mman.h> /* shm_open ... */
#include <sys/stat.h> /* For mode consts */
#include <unistd.h> /* ftruncate */
#define BUF_SIZE 1024
typedef struct Payload_ {
int a;
int b;
char buf[BUF_SIZE];
} Payload;
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s /shm-path\n", argv[0]);
exit(EXIT_FAILURE);
}
const char* shm_path = argv[1];
int fd = shm_open(shm_path, O_RDWR, 0);
if (fd == -1) {
perror("shm_open");
exit(EXIT_FAILURE);
}
Payload* payload =
mmap(NULL, sizeof(Payload), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (payload == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
printf("SHMEM content: %s\n", payload->buf);
shm_unlink(shm_path);
return 0;
}
#include <fcntl.h> /* for O_* consts */
#include <stdio.h> /* print */
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <sys/mman.h> /* shm_open ... */
#include <sys/stat.h> /* For mode consts */
#include <unistd.h> /* ftruncate */
#define BUF_SIZE 1024
typedef struct Payload_ {
int a;
int b;
char buf[BUF_SIZE];
} Payload;
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s /shm-path\n", argv[0]);
exit(EXIT_FAILURE);
}
const char* shm_path = argv[1];
int fd = shm_open(shm_path, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("shm_open");
exit(EXIT_FAILURE);
}
if (ftruncate(fd, sizeof(Payload)) == -1) {
perror("truncate");
exit(EXIT_FAILURE);
}
Payload* payload =
mmap(NULL, sizeof(Payload), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (payload == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
memcpy(&payload->buf, "HELLO\0", 6);
/**
* Unlink the shared memory object. Even if the peer process
* is still using the object, this is okay. The object will
* be removed only after all open references are closed.
*/
// shm_unlink(shm_path);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment