- 论坛徽章:
- 0
|
以下是我的编程风格,希望大家多多指教
- /******************************************************************
- * Desc : 信号量操作函数
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <errno.h>;
- #include <sys/sem.h>;
- #include <sys/signal.h>;
- #include <sys/wait.h>;
- union semun {
- int val;
- struct semid_ds *buf;
- ushort *array;
- } arg;
- struct sembuf Post= {
- 0, 1, 0
- };
- struct sembuf Wait= {
- 0, -1, 0
- };
- /******************************************************************
- * Function : semWait
- * Desc : 等待信号
- * Para : semid - 信号ID
- * Return : -1 - fail
- * 0 - sucess
- *
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- semWait(int semid)
- {
- while (semop(semid, &Wait, 1)) {
- if (errno == EINTR) {
- _Sleep(1);
- }
- else {
- perror("semop");
- return(-1);
- }
- }
- return(0);
- }
- /******************************************************************
- * Function : semPost
- * Desc : 释放信号
- * Para : semid - 信号ID
- * Return : -1 - fail
- * 0 - sucess
- *
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- semPost(int semid)
- {
- if (semop(semid, &Post, 1)) {
- perror("semop");
- return(-1);
- }
- return(0);
- }
- /******************************************************************
- * Function : semInit
- * Desc : 初始信号
- * Para : semKey - 信号关键字
- * val - 信号量初始值
- * Return : -1 - fail
- * >;0 - sucess
- *
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- semInit(key_t semKey, int val)
- {
- int semid;
- if ((semid = semget((key_t)semKey, 1, 0755|IPC_CREAT|IPC_EXCL))<0) {
- if (errno == EEXIST) {
- if ((semid = semget(SEM_KEY, 1, 0755))<0)
- return(-1);
- }
- }
- arg.val = val;
- if ((semctl(semid, 0, SETVAL, arg))<0) {
- perror("semctl");
- return(-1);
- }
- return(semid);
- }
- /******************************************************************
- * Function : semGetVal
- * Desc : 得到信号量值
- * Para : semid - 信号ID
- * Return : -1 - fail
- * ? - sucess
- *
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- int semGetVal(int semid)
- {
- int semNum;
- if ((semNum=semctl(semid, 0, GETVAL, 0)) < 0) {
- perror("semctl");
- return(-1);
- }
- return(semNum);
- }
- /******************************************************************
- * Function : _Sleep()
- * Desc : sleep 0-指定时间
- * Para : t - 想要sleep的最大时间
- * Return :
- *
- * Author :
- * Date : 05/30/2003
- *
- *****************************************************************/
- _Sleep(int t)
- {
- int num = 1+(int)((double)t*rand()/(RAND_MAX+1.0));
- sleep(num);
- }
复制代码 |
|