Created
December 17, 2015 15:16
-
-
Save apfohl/c3603f79b444495e5187 to your computer and use it in GitHub Desktop.
Shared memory example
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
| #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