Semaphores

This is a discussion on Semaphores within the C++ Programming forums, part of the General Programming Boards category; OK, after my last thread on this subject failed miserably, I am trying again. How do I go about creating ...

  1. #1
    edk
    edk is offline
    Registered User
    Join Date
    Sep 2001
    Posts
    20

    Semaphores

    OK, after my last thread on this subject failed miserably, I am trying again.

    How do I go about creating and unlocking a set of 5 System V semaphores? Once this is done, how do I wait for them, and signal when I'm finished using it?

    I'm trying to fork 5 children and execute their functions in a user-specified order. There are 5 children, so there should be a set of 5 semaphores. The user enters the order of execution (integer between 1 and 5, inclusive) using the keyboard. I fork the 5 children all at once, but I need to synchronize their execution with semaphores. How do I do this?

    Also, please post code examples, not links to other pages. I have tried many other pages but they confuse me more than they help.

    Thanks in advance.
    liberate tutamet ex inferis

  2. #2
    edk
    edk is offline
    Registered User
    Join Date
    Sep 2001
    Posts
    20
    Here's the code segment for what i am doing:

    Code:
    	for (int i(0); i < theOrder.size(); i++) {
    		pid = fork();
    		if (pid < 0) {
    			cerr<<"ERROR:  fork error\n";
    			exit(0);
    		}
    		else if (pid == 0) {
    			// wait for semaphore here (code not written yet
    			doChildStuff(i);
    			// signal semaphore here (code not written yet
    
    			exit(0);
    		}
    		childPid[children] = pid;
    		children++;
    	}
    ...and here's my creation of the semaphore set:
    Code:
    	sem_key = 0x2222;
    	if ((sem_id = semget(sem_key, theOrder.size(), 0666 | IPC_CREAT)) == -1) {
    		cerr<<"ERROR:  semget error\n";
    	}
    	
    	arg.val = 1;
    	for (int i(0); i < theOrder.size(); i++) {
    		if (semctl(sem_id, i, SETVAL, arg) == -1) {
    			cerr<<"semctl error\n";
    		}
    	}
    you can see, all o the semaphores are initialized to 1. now that you know this, how do i make it so that the first semaphore is signalled? also, how do i wait for a semaphore?
    liberate tutamet ex inferis

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Semaphores, need advice on implementation.
    By Swerve in forum C++ Programming
    Replies: 2
    Last Post: 01-13-2009, 12:54 AM
  2. semaphores
    By Dr Spud in forum C Programming
    Replies: 7
    Last Post: 09-22-2007, 12:45 PM
  3. Semaphores Problems
    By mhelal in forum Linux Programming
    Replies: 2
    Last Post: 05-06-2007, 10:36 PM
  4. Semaphores
    By Jules in forum C Programming
    Replies: 4
    Last Post: 01-18-2004, 12:58 PM
  5. semaphores
    By theLukerBoy in forum C Programming
    Replies: 0
    Last Post: 11-05-2002, 12:46 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21