01 Show me the code
#include <sys/shm.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
const int create_shm_flag(const int INDEX, const unsigned int LENGTH) {
key_t key = ftok("./", INDEX);
const int FLAG = shmget(key, LENGTH, IPC_CREAT | IPC_EXCL | 0666);
assert(FLAG >= 0);
return FLAG;
}
const int get_shm_flag(const int INDEX, const unsigned int LENGTH) {
key_t key = ftok("./", INDEX);
const int FLAG = shmget(key, LENGTH, IPC_CREAT | 0666);
assert(FLAG >= 0);
return FLAG;
}
int main() {
const int FLAG_X = create_shm_flag(111, sizeof(int));
int* x = (int*)shmat(FLAG_X, NULL, SHM_R | SHM_W);
int id = fork();
assert(id >= 0);
if (id > 0) {
(*x) += 1;
printf("pid= %d, x_address= %x, x= %d\n", getpid(), x, *x);
} else {
usleep(100);
printf("pid= %d, x_address= %x, x= %d\n", getpid(), x, *x);
}
if (id > 0) {
sleep(1);
shmctl(FLAG_X, IPC_RMID, NULL);
}
return 0;
}