named semaphore wont work as assumed in synchronization between process

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%sn", 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: %pn", 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("%dn", 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật