2 Replies - 1592 Views - Last Post: 05 March 2011 - 12:57 PM Rate Topic: -----

#1 monicojr84  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 27
  • Joined: 11-February 11

POSIX Semaphores

Posted 05 March 2011 - 10:46 AM

Firstly, can you use Posix Semaphores with Sys V Shared memory. And secondly for interprocess communication do you named or unnamed POSIX semaphores. I am trying to use named semaphores but I get a segmentation fault when I call sem_wait().


int main()
{ int choice;
  int shmid;
  int result;
  int first = 0;
  key_t shmKey = 1234;
  key_t semKey = 5678;
  Reserve *shared;
  sem_t * sem;

  //create the shared memory segment if the 1st process
  shmid = shmget(shmKey, 120*sizeof(Reserve), 0666 | IPC_CREAT| IPC_EXCL);
  //Create and initialize semaphore 
   sem = (sem_t*)semop("/sem", O_CREAT | O_EXCL, 0666, 1);

  if((shmid != -1) && (semid != 1))
    { //Connect to the shared memory segment
      shared =(Reserve *)shmat(shmid, NULL, 0); 
      first = 1;
      if(first == 1)
	//initialize structs
	initialize(shared);
    }
  else 
    { shmid = shmget(shmKey, 120*sizeof(Reserve), 0666);
      //Connect to the shared memory segment
      shared =(Reserve *)shmat(shmid, NULL, 0); 

      sem = (sem_t*)semop("/sem", 0);  //access if semaphore already exists
    }
  
  //Display choices to user
  choice = displayMenu();

  //Determine which function to call for the users input
  while(1)
    {switch(choice)
	{ case 1:
	    sem_wait(sem);  //I get a seg, fault here, after I chose 1 
	     allSeats(shared);
	     sem_post(sem); break;
	  case 2:
	    sem_wait(sem);
	    reserveSeat(shared);
	    sem_post(sem); break;
	  case 3:
	    sem_wait(sem);
	    openSeats(shared);
	    sem_post(sem); break;
	default:
	  printf("Invalid choice, Please try again.\n"); break;
	}//End of switch




This post has been edited by monicojr84: 05 March 2011 - 10:47 AM


Is This A Good Question/Topic? 0
  • +

Replies To: POSIX Semaphores

#2 apw5020  Icon User is offline

  • D.I.C Addict

Reputation: 78
  • View blog
  • Posts: 666
  • Joined: 26-March 09

Re: POSIX Semaphores

Posted 05 March 2011 - 11:02 AM

I'm not familiar with this function: sem = (sem_t*)semop("/sem", O_CREAT | O_EXCL, 0666, 1) I've always used this: sem_init(&sem, 0, 0). Also, try using a reference: sem_wait(&sem).

This post has been edited by apw5020: 05 March 2011 - 11:13 AM

Was This Post Helpful? 0
  • +
  • -

#3 Salem_c  Icon User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 1770
  • View blog
  • Posts: 3,428
  • Joined: 30-May 10

Re: POSIX Semaphores

Posted 05 March 2011 - 12:57 PM

I must be missing something, because your semop() calls look nothing like the prototype shown here.
http://pubs.opengrou.../xsh/semop.html

On the face of it, you're passing random garbage to the function, so yeah, it crashes.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1