File: ipc.c

package info (click to toggle)
cwirc 1.8.8-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 640 kB
  • ctags: 585
  • sloc: ansic: 5,399; makefile: 292
file content (126 lines) | stat: -rw-r--r-- 2,230 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/* CWirc - X-Chat plugin for sending and receiving raw morse code over IRC
   (c) Pierre-Philippe Coupard - 18/06/2003

   IPC routines

   This program is distributed under the terms of the GNU General Public License
   See the COPYING file for details
*/
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>

#include "ipc.h"



/* Create a semaphore set. */
int cwirc_sem_create(int key,int nb_sems)
{
  struct sembuf sops;
  int semid;
  int i;

  /* Create the semaphore set */
  if((semid=semget(key,nb_sems,IPC_CREAT | 0600))==-1)
    return(-1);

  /* Wait for the semaphore to reach 1 */
  for(i=0;i<nb_sems;i++)
  {
    sops.sem_num=i;
    sops.sem_op=1;		/* wait for semaphore flag to become 1 */
    sops.sem_flg=SEM_UNDO;
    if(semop(semid,&sops,1)==-1)
    {
      semctl(semid,0,IPC_RMID,0);
      semid=-1;
      return(-1);
    }
  }

  return(semid);
}



/* Decrement a semaphore */
int cwirc_sem_dec(int semid,int semnum)
{
  struct sembuf sops;

  sops.sem_num=semnum;
  sops.sem_op=-1;		/* decrement semaphore == P() */
  sops.sem_flg=SEM_UNDO;
  if(semop(semid,&sops,1)==-1)
    return(-1);

  return(0);
}



/* Increment a semaphore */
int cwirc_sem_inc(int semid,int semnum)
{
  struct sembuf sops;

  sops.sem_num=semnum;
  sops.sem_op=1;		/* increment semaphore == V() */
  sops.sem_flg=SEM_UNDO;
  if(semop(semid,&sops,1)==-1)
    return(-1);

  return(0);
}



/* Destroy the semaphore */
int cwirc_sem_destroy(int semid)
{
  if(semid<0 || semctl(semid,0,IPC_RMID,0)==-1)
    return(-1);

  return(0);
}



/* Allocate a shared memory block. Return code :
   shared memory id
   -1 : error allocating the shared memory */
int cwirc_shm_alloc(int key,int size)
{
  return(shmget(key,size,IPC_CREAT | 0600));
}



/* Attach the shared memory block. Return code :
   pointer to the shared memory block
   -1 : error attaching to the shared memory block */
void *cwirc_shm_attach(int shmid)
{
  return(shmat(shmid,NULL,0));
}



/* Detach the shared memory block. */
int cwirc_shm_detach(void *shm)
{
  return(shmdt(shm));
}



/* Free the shared memory block */
int cwirc_shm_free(int shmid)
{
  if(shmid<0 || shmctl(shmid,IPC_RMID,0)==-1)
    return(-1);

  return(0);
}