Skip to content

Instantly share code, notes, and snippets.

@apfohl
Created December 17, 2015 15:16
Show Gist options
  • Save apfohl/c3603f79b444495e5187 to your computer and use it in GitHub Desktop.
Save apfohl/c3603f79b444495e5187 to your computer and use it in GitHub Desktop.
Shared memory example
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
/* shared memory segment */
int shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
return EXIT_FAILURE;
}
int *state = shmat(shmid, NULL, 0);
if (*state == -1) {
perror("shmat");
return EXIT_FAILURE;
}
*state = 0;
pid_t pid = fork();
if (pid == 0) {
int *temp = shmat(shmid, NULL, 0);
*temp = 42;
shmdt(temp);
} else {
int stat_loc = 0;
waitpid(pid, &stat_loc, 0);
char *sig_str = strsignal(WTERMSIG(stat_loc));
printf("{\"state\": %d, \"stat_loc\": %d, \"signal\": \"%s\"}\n", *state, stat_loc, sig_str);
free(sig_str);
if (shmdt(state) == -1) {
perror("shmdt");
return EXIT_FAILURE;
}
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment