semdemo1 - perror (argv[0]); exit(1); } creator = 0; } if...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
// semdemo1.cpp / #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <iostream.h> # const int DUMMY = 0; const int COUNT = 4; c void main(int argc, char *argv[] ) { key_t ipckey; int semid, pid; int creator, i; static struct sembuf lock = { 0, -1, SEM_UNDO }; static struct sembuf unlock = { 0, 1, SEM_UNDO }; { pid = getpid(); setbuf(stdout, (char *) NULL); ipckey = ftok(argv[0], 's'); if ( (semid = semget(ipckey, 1, IPC_CREAT | IPC_EXCL | 0666) ) != -1) { creator = 1; } else { // semget failed since key already exists, try to get semid / if ( (semid = semget(ipckey, 1, 0) ) == -1) {
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: perror (argv[0]); exit(1); } creator = 0; } if (creator) { // initialize semaphore if (semctl (semid, 0, SETVAL, 1) == -1) { perror (argv[0]); exit(2); } } for (i = 0; i &lt; COUNT; i++) { if (semop(semid, &amp;lock, 1) == -1) { perror(argv[0]); exit(3); } cout &lt;&lt; &quot;[&quot; &lt;&lt; pid &lt;&lt; &quot;] locking\t&quot;; sleep(1); // output to monitor cout &lt;&lt; &quot;[&quot; &lt;&lt; pid &lt;&lt; &quot;] unlocking&quot; &lt;&lt; endl; if (semop(semid, &amp;unlock, 1) == -1) { perror (argv[0]); exit(4); } } if (creator) { sleep(5); if (semctl (semid, DUMMY, IPC_RMID, DUMMY) == -1) { perror (argv[0]); exit(5); } } }...
View Full Document

Page1 / 2

semdemo1 - perror (argv[0]); exit(1); } creator = 0; } if...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online