0

all

I am working on a Linux multi-process application which has no parent-children relation when running and looking for the way to synchronize its processes.

I tried pthread semaphore but faced one problem. After some processes increment a value of a semaphore and finish its execution immediately, the value of the semaphore is not reset while no process holds the semaphore. Therefore, on a next execution, the program wait for the semaphore to be 0 forever and do not make a progress.

So that, POSIX semaphore is vulnerable to aborting. System V also has the same problem.

Here is a code in which I examined the problem.

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

namespace
{
    void run(void)
    {
        sem_t *s;
        s = sem_open("/sem", O_CREAT, 0666, 1);
        if(!s){
            perror("On opening semaphore");
            return;
        }

        cout << "wait lock" << endl;
        sem_wait(s);
        cout << "aquired lock" << endl;
        sleep(5);
        sem_post(s);
        cout << "released lock" << endl;

        sem_close(s);
    }
}

int main(void)
{
    run();

    return 0;
}

Could anybody tell me an alternative way to synchronize processes after aborting.

Thank you,

nutsman
  • 331
  • 2
  • 10

0 Answers0