Comment on attachment 839408 [details]
The fist c-Programm
The second c-programm:
/* y.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h> // IPC_NOWAIT = 0x800, SEM_UNDO = 0x1000
#include <sys/sem.h>
#include <errno.h>
enum {LOCK_SEMA=-1, UNLOCK_SEMA=1};
#define KEY 1234567L
static int semid = -1;
static int printSemaValue(int line, const char *pStr) {
int semVal0(0), semVal1(0);
semVal0 = semctl (semid, 0, GETVAL);
if (semVal0 < 0) {
printf ("In Line %d: retcode < 0 from semctl (%d, 0, GETVAL), errno =
%d\n\n", __LINE__-2, semid, errno);
return semVal0;
}
semVal1 = semctl (semid, 1, GETVAL);
if (semVal1 < 0) {
printf ("In Line %d: retcode < 0 from semctl (%d, 1, GETVAL), errno =
%d\n\n", __LINE__-2, semid, errno);
return semVal1;
}
printf ("\n");
printf ("semVal0 GETVAL %d\n", semVal0);
printf ("semVal1 GETVAL %d\n%s, in Line %d\n", semVal1, pStr, line);
return 1;
}
static int init_semaphore (void) {
int semVal0(0), semVal1(0);
semid = semget (KEY, 0, IPC_PRIVATE);
if (semid < 0) {
printf ("\n Line %d: sema was not created\n", __LINE__-2);
return semid;
}
semVal0 = semctl (semid, 0, GETVAL);
if (semVal0 < 0) {
printf ("In Line %d: retcode < 0 from semctl (%d, 0, GETVAL), errno =
%d\n\n", __LINE__-2, semid, errno);
return semVal0;
}
semVal1 = semctl (semid, 1, GETVAL);
if (semVal0 < 0) {
printf ("In Line %d: retcode < 0 from semctl (%d, 1, GETVAL), errno =
%d\n\n", __LINE__-2, semid, errno);
return semVal1;
}
return 1;
}
static int semaphoreOp (int op, int semNum) {
struct sembuf semaphore [] = {(unsigned short) semNum, (short) op, (short)
SEM_UNDO};
if( semop (semid, semaphore, 1) == -1) {
return -1;
}
return 1;
}
int main (void) {
long loop, res;
int lineNr (-1);
int myError(0);
res = init_semaphore ();
if (res < 0) {
printf ("\nretcode < 0 from init_semaphore\n");
semctl(semid, 1, IPC_RMID, 0);
return res;
}
printSemaValue(__LINE__, "init_semaphore() was successful");
for (loop =0; myError==0; ++loop) {
printf ("\nloop = %ld\n", loop);
res = semaphoreOp (LOCK_SEMA, 1);
lineNr =__LINE__ -1;
if (res < 0) {
int semVal0(0), semVal1(1);
myError = errno;
if (myError == EIDRM) {
printf ("In Line %d: LOCK_SEMA, sem_num 1, was not
successful;\nerrno = %d (=EIDRM, Identifier removed)\n\n",
lineNr, myError);
}
else {
printf ("In Line %d: LOCK_SEMA, sem_num 1, was not
successful;\nerrno = %d\n\n",
lineNr, myError);
}
break;
}
// sleep (1);
res = semaphoreOp (UNLOCK_SEMA, 0);
lineNr =__LINE__ -1;
if (res < 0) {
int semVal0(0), semVal1(1);
myError = errno;
if (myError == EIDRM) {
printf ("In Line %d: UNLOCK_SEMA, sem_num 0, was not
successful;\nerrno = %d (=EIDRM, Identifier removed)\n\n",
lineNr, myError);
}
else {
printf ("In Line %d: UNLOCK_SEMA, sem_num 0, was not
successful;\nerrno = %d\n\n",
lineNr, myError);
}
break;
}
printf ("\n");
} // for ...
// semctl(semid, 0, IPC_RMID, 0);
return 1;
}