given writer & reader code as follows, the program just wont work as it assumed to be:
expect behavior: after we launch the writer, then after typically 2s, we startup reader from another terminal, due to semaphore protection, the reader should block waiting on the semaphore to be 1, and then print out the derived msg.
however, the outcome is quite the opposite.
firstly, we launch the writer process in a terminal, the output is as:
shared mem address: 0x10cc68000 [0..511]
backing file: /dev/shm/shMemEx
8
7
6
5
4
3
2
1
wait for namely 2s, then run the reader process, while almost immediately, the reader print out the semaphore 'protected' data:
mac@mbp cpp % ./r
hello worldThis is the way the world ends...
writer.c:
// compilation on macos: gcc -o w writer.c -lpthread
// compilation on linux: gcc -o w writer.c -lrt -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
#include "shmem.h"
int main(){
int fd = shm_open(BackingFile, O_RDWR | O_CREAT, AccessPerms); // r/w + create
if(fd < 0){
report_and_exit("can't open shared mem segment");
}
ftruncate(fd, ByteSize); // adjust the backing file size
caddr_t memptr = mmap(
NULL, // let system pick shared mem seg pos
ByteSize, // bytes
PROT_READ | PROT_WRITE, // access protections
MAP_SHARED, // shared mem visible to other proc
fd, // fd
0 // offset: start at 0
);
if((caddr_t) -1 == memptr){ // mmap creation check
report_and_exit("can't get segment...");
}
fprintf(stderr, "shared mem address: %p [0..%d]\n", memptr, ByteSize - 1);
fprintf(stderr, "backing file: /dev/shm%s\n", BackingFile );
sem_t* semptr = sem_open( // create semaphore to lock the shared mem
SemaphoreName, // name
O_CREAT, // op = create
AccessPerms, // protection perms
0 // init value
);
if(semptr == (void*) -1){ // semaphore creation check
report_and_exit("sem_open");
}
// fprintf(stderr, "semaphore address: %p\n", semptr);
strcpy(memptr, MemContents); // write to mem (copy ascii bytes to shared mem seg)
int num = 8; // wait 8s -> reader should not access
while(num > 0){
printf("%d\n", num);
num--;m
sleep(1);d
}
if(sem_post(semptr) < 0){ // incr semaphore after writing finish, let reader access
report_and_exit("sem_post");
}
sleep(6); // for reader to be scheduled
// cleanups
munmap(memptr, ByteSize); // unmap the storage
close(fd);
sem_close(semptr);
shm_unlink(BackingFile); // unlink from the backing file
return 0;
}
reader.c
// compilation on macos: gcc -o r reader.c -lpthread
// compilation on linux: gcc -o r reader.c -lrt -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
#include "shmem.h"
int main(){
int fd = shm_open(BackingFile, O_RDWR, AccessPerms); // r/w without create
if(fd < 0){
report_and_exit("can't get file descriptor...");
}
caddr_t memptr = mmap( // ptr to mem
NULL, // let system pick mem seg pos
ByteSize, // bytes of shared mem
PROT_READ | PROT_WRITE, // access protections
MAP_SHARED, // shared mem is visible to other proc
fd, // fd
0 // offset: start at 0
);
if((caddr_t) -1 == memptr){ //
report_and_exit("can't access segment...");
}
sem_t* semptr = sem_open( // semaphore as mutex
SemaphoreName, // name
O_CREAT, // create semaphore if not existed
AccessPerms, // protection perms
0 // init val
);
if(semptr == (void*) -1){ // err return if semaphore create failed (non-block)
report_and_exit("sem_open");
}
if(!sem_wait(semptr)){ // wait until semaphore != 0, then start reading
int i;
for(i=0; i<strlen(MemContents); i++){
write(STDOUT_FILENO, memptr+i, 1); // one byte at a time
}
sem_post(semptr); // incr semaphore by 1
}
munmap(memptr, ByteSize); // cleanup
close(fd);
sem_close(semptr);
unlink(BackingFile); // if omitted, file will persist after program exit
return 0;
}
shmem.h
#define ByteSize 512
#define BackingFile "/shMemEx"
#define AccessPerms 0644
#define SemaphoreName "mysemaphore"
#define MemContents "This is the way the world ends...\n"
void report_and_exit(const char* msg){
perror(msg);
exit(-1);
}
the code source: https://opensource.com/sites/default/files/gated-content/inter-process_communication_in_linux.pdf
Your semaphore is not being cleaned up properly. You need to add a sem_unlink() to the writer to "really" destroy the semaphore. If you don't all of the sem_opens() will just get whatever value the semaphore last had (and the reader does a sem_post after printing the results so it's not 0)
You can confirm by trying to open with O_CREAT | O_EXCL in the writer which will tell you the semaphore already exists.