b.cpp
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <unistd.h>
#include <stdlib.h>
void child() {
printf("child\n");
return;
}
int main() {
// get key
key_t shmKey = ftok("/tmp", 1);
key_t semKey = ftok("/tmp", 2);
printf("shmkey = %d semkey = %d\n", (int)shmKey, (int)semKey);
// create shm
int shmid = shmget(shmKey, 3 * sizeof(int), IPC_CREAT | 0600);
printf("shm id %d\n", shmid);
// attach shm
int *shm = (int *) shmat(shmid, NULL, 0);
printf("shm ptr %p\n", shm);
// create sem
int semid = semget(semKey, 2, IPC_CREAT | 0600);
sleep(3);
// detach shm
shmdt(shm);
// remove shm
shmctl(shmid, IPC_RMID, 0);
int pid = fork();
if(pid == 0) {
child();
exit(0);
}
printf("main\n");
return 0;
}
a.cpp
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
void make(int id) {
srand(time(0));
for(int i=0;i<6;i++) {
// add data
usleep(rand() % 1000000);
int data = rand();
printf("W-%d-%d -> %d\n", id, i, data);
}
}
void use(int id) {
srand(time(0));
for(int i=0;i<6;i++) {
// get data
usleep(rand() % 1000000);
int data;
data = rand();
printf("R-%d-%d <- %d\n", id, i, data);
}
}
int main() {
int *child = (int*)malloc(5*sizeof(int));
int child_cnt;
for(int i=0;i<2;i++) {
// maker
int pid = fork();
if(pid == 0) {
// child process
make(i);
exit(0);
}
else {
child[child_cnt++] = pid;
}
}
for(int i=0;i<3;i++) {
// user
int pid = fork();
if(pid == 0) {
use(i);
exit(0);
}
else {
child[child_cnt++] = pid;
}
}
for(int i=0;i<child_cnt;i++) {
waitpid(child[i], NULL, 0);
}
return 0;
}