Semaphore operations on Suns
Pilli Sujata
sujata at herky.cs.uiowa.edu
Sat Jun 30 12:48:57 AEST 1990
The folowing code is performing some Semaphore operations like wait and
signaling System V features. But I have problems when I am running it on
The Sun (3/50, 3/60 ) SUN O.S RELEASE 4.0. The semaphore results in a
negative value sometimes. The same code was run on a different m/c the
Encore which has the same system calls and it ran fine. Could anyone tell
me why it is not working on the Suns? Please do run it several times.
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/wait.h>
main()
{
int i, semid,status, x;
struct sembuf cw,cs,pw,ps;
if ((semid=semget(IPC_PRIVATE,2,0666))==-1) perror("semget");
cw.sem_num = 1; cw.sem_op = -1; cw.sem_flg =~IPC_NOWAIT;
cs.sem_num = 0; cs.sem_op = 1; cs.sem_flg = IPC_NOWAIT;
pw.sem_num = 0; pw.sem_op = -1; pw.sem_flg =~IPC_NOWAIT;
ps.sem_num = 1; ps.sem_op = 1; ps.sem_flg = IPC_NOWAIT;
if ( fork() == 0) {
/* child */
/*Get semaphore value for 1 */
if ((x = semctl(semid,1,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by child for sem 1 %d\n",x);
/*semaphore wait */
if(semop(semid, &cw, 1) == -1) perror("child-not-waiting:semop1");
/*Get semaphore value for 1 */
if ((x = semctl(semid,1,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by child for sem 1 %d\n",x);
/*Get semaphore value for 0 */
if ((x = semctl(semid,0,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by child for sem 0 %d\n",x);
/*semaphore signal*/
if(semop(semid, &cs, 1) == -1) perror("child-signals:semop2");
/*Get semaphore value for 0 */
if ((x = semctl(semid,0,GETVAL,0)) == -1) perror("no-prob:semctl3");
printf("Semval read by child for sem 0 %d\n",x);
}
else {
/*parent*/
/*Get semaphore value for 1 */
if ((x = semctl(semid,1,GETVAL,0)) == -1) perror("no-prob:semctl3");
printf("Semval read by Parent for sem 1 %d\n",x);
/*semaphore signal*/
if(semop(semid, &ps, 1) == -1) perror("par-signals:semop2");
/*Getsemaphore value for 0 & 1 */
if ((x = semctl(semid,0,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by Parent for sem 0 %d\n",x);
if ((x = semctl(semid,1,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by Parent for sem 1 %d\n",x);
/*semaphore wait*/
printf("Parent shud wait\n");
if(semop(semid, &pw, 1) == -1) perror("parent-waits:semop2");
/*Get semaphore value for 0 */
if ((x = semctl(semid,0,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by Parent for sem 0 %d\n",x);
if ((x = semctl(semid,1,GETVAL,0)) == -1) perror("no-prob:semctl1");
printf("Semval read by Parent for sem 1 %d\n",x);
/*wait for child*/
while (wait(&status) == -1) perror("wait");
}
semctl(semid,0,IPC_RMID,0);
}
Please e-mail you responses.
Thanks
Sujata
sujata at zambini.cs.uiowa.edu
More information about the Comp.sys.sun
mailing list