/* 
**
** ipcfunc.c
**
*/

#include "../include/includes.h"

void *
ShmInit(int shm_id, char *prog_name, key_t key, int size, int shmflg)
{
void       *retp;
char       *func_name = "ShmInit";

    shm_id = shmget(key, size, shmflg);
    if (shm_id == -1)
        log_sys("%s: %s: shmget(key: %x)", prog_name, func_name, key);
        
    retp = shmat(shm_id, (char *)0, 0);
    if (retp == (void *) -1)
        log_sys("%s: %s: shmat", prog_name, func_name);
    
    return retp;
}

int
SemInit(char *prog_name, key_t key, int sem_num, int sem_flg)
{
int           initarray[sem_num];
int           sem_id, retval, i;
char          *func_name = "SemInit";

    sem_id = semget(key, sem_num, sem_flg);
    if (sem_id == -1)
        log_sys("%s: %s: semget", prog_name, func_name);
    for (i=0; i<sem_num; i++) {
        initarray[i] = 1;
  		retval = semctl(sem_id, i, SETVAL, initarray[i]);
    	if (retval == -1)
       		log_sys("%s: %s: semctl", prog_name, func_name);
	}
    
    return sem_id;
}

BOOL
SemLock(char *prog_name, int sem_id, int sem_num, unsigned nsops, int sem_flg)
{
int               retval;
struct sembuf     lock = {0, -1, SEM_UNDO};

    lock.sem_num = sem_num;
    lock.sem_flg |= sem_flg;    
    retval = semop(sem_id, &lock, nsops);
    if (retval == -1) {
    //    char    *func_name = "SemLock";
   //     log_ret("%s: %s: semop(%d)", prog_name, func_name, sem_num);
        return -1;
    }

    return 0;
}

BOOL 
SemUnlock(char *prog_name, int sem_id, int sem_num, unsigned nsops, int sem_flg)
{
int               retval;
struct sembuf     unlock = {0, 1, IPC_NOWAIT|SEM_UNDO};

    unlock.sem_num = sem_num;
    unlock.sem_flg |= sem_flg;
    retval = semop(sem_id, &unlock, nsops);
    if (retval == -1) {
//        char    *func_name = "SemUnlock";
//        log_ret("%s: %s: semop(%d)", prog_name, func_name, sem_num);
        return -1;
    }

    return 0;
}

