[QUERY] Help With Semaphore Error on Windows : Cygwin

Yeo Kai Wei yeokaiwei@hotmail.com
Thu Feb 16 04:04:01 GMT 2023

Hi All,

Could I request for some help on some code?

I ran into an error with semaphores with some book code using Cygwin on 

The code will throw an error with sem_post().

I compiled it with gcc -o memwriter memwriter.c -lrt -lpthread

$ ./memwriter
Shared memory address: 0x6fffffff0000 [0..511]
backing file: /dev/shm/shMemEx
semptr is address 0x7ffffcc18 with value 0
SEM_VALUE_MAX is 1147483648
sem_post: Invalid argument <--------------------------- ERROR

According to feedback, the above error does not turn up on Linux.

May I know if this is supposed to happen on Cygwin on Windows?

If not, how can I solve this?

I've also attached the code for reference.

Thank you.

Kind regards,

YEO Kai Wei

-------------- next part --------------
#define ByteSize 512
#define BackingFile "/shMemEx"
#define AccessPerms 0644
#define SemaphoreName "mysemaphore"
#define MemContents "This is the way the world ends...\n"
-------------- next part --------------
//gcc -o memwriter memwriter.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 <limits.h> //SEM_VALUE_MAX

#include "shmem.h"

void report_and_exit(const char* msg)


int main()
	//Create file descriptor
	int fd = shm_open(	BackingFile, 
				O_RDWR | O_CREAT, 	//Read, write, create if needed
				AccessPerms); 		//Access permission 0644

		report_and_exit("Can't open shared mem segment ... ");

	//Get the bytes
	ftruncate(fd, ByteSize);

	//Let system pick where to put the segments
	caddr_t memptr = mmap(	NULL, 			//Let system pick
				ByteSize, 		//How many bytes
				PROT_READ | PROT_WRITE, //Access protections
				MAP_SHARED, 		//Mapping visible 
				fd, 			//file descriptor
				0); 			//offset 0, start from 1st byte

	if((caddr_t) -1 == memptr)
		report_and_exit("Can't get segment...");

	fprintf(stderr, "Shared memory address: %p [0..%d]\n", memptr, ByteSize -1);
	fprintf(stderr, "backing file: /dev/shm%s\n", BackingFile);

	//Create the semaphore
	sem_t* semptr = sem_open(	SemaphoreName,//name 
					O_CREAT, //create semaphore
					AccessPerms, //protection permissions
					0);	//Initial value

	if(semptr == (void*) -1)

	//Copy some ASCII Bytes to the memory segment
	strcpy(memptr, MemContents);

	printf("semptr is address %p with value %i\n", &semptr, semptr);
	printf("SEM_VALUE_MAX is %i\n", SEM_VALUE_MAX);

	//sem_post increments the semaphore -1 ERROR, 0 success
	if(sem_post(semptr) < 0) 


	//Cleanup. Unmap the storage
	munmap(memptr, ByteSize);



	//Unlink from backing file

	return 0;

More information about the Cygwin mailing list