Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

It’s been almost 2 decades since I did any C programming. Rust doesn’t even begin to describe the difficulties. We had a small programmed that wrapped the Comscire provided C API that needed to be protected from multiple processes accessing the hardware at the same time. Enter the C Named Semaphore. I found several examples, but none of them was a complete example. That’s a shame. The incomplete examples made it that much harder to get working.

Semaphores in Linux was an invaluable resource.

  • Line 4 and 5 are the headers necessary. Semaphore and file control.
  • Line 8 – the name of the named semaphore
  • Line 9– declared the semaphore
  • Line 33 – The semaphore is opened. O_CREATE specifies that the semaphore is created if it doesn’t already exist. The name of the semaphore is specified here.
  • Line 39 – locks the semaphore. This prevents other processes from accessing the code while another process is accessing the protected section.
  • Line 45 – unlocks the semaphore
  • Line 47 – closes the named semaphore
  • Line 49 – deletes the named semaphore. Without this, only you will be able to run the program. The name of the semaphore is specified here.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <qwqng.hpp>

char semaphoreName[] = "rng_semaphore";
sem_t *namedSemaphore;

 Performs the call to retrieve a random integer.
 returnCount - the number of random integers to return
void doRandCall(int returnCount)
  // omitted for brevity

 Returns a specified number of random integers from the Comscire hardware RNG.
 argc - count of arguments
 argv - process parameters
 [0] - number of random integers to generate
int main(int argc, char *argv[])
    if (argc == 2)
        int returnCount = atoi(argv[1]);
        if ((namedSemaphore = sem_open(semaphoreName, O_CREAT, 0644, 1)) == SEM_FAILED)
            perror("named semaphore initialization error");
        return EXIT_SUCCESS;

January 7th, 2015

Posted In: Javaninja

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By :