- 论坛徽章:
- 0
|
我实现了一个信号量的程序.
主进程循环创建5个子进程并使它们争夺数值为3的信号量.
下面是我的程序,可以运行,但觉得很麻烦,我想知道有比较简便的方法吗.
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unsitd.h>
- #include <errno.h>
- union semun{
- int val;
- struct semid_ds *buf;
- unsigned short int *array;
- };
- void print(int);
- int value;
- int main(int argc,char **argv)
- {
- int n=0;
- int id;
- struct sembuf lock_it);
- union semun options;
- if((id=semget(ftok(argv[1],0),1,IPC_CREAT|IPC_EXCL|0666))==-1)
- perror(“semget”);
- options.val=3;
- semctl(id,0,SETVAL,options);
- while(n++<5)
- {
- if(fork()==0)
- {
- while(0)
- {
- lock_it.sem_num=0;
- lock_it.sem_op=-1;
- lock_it.sem_flg=IPC_NOWAIT;
- if((semop(id,&lock_it,1))==-1)
- {
- if(errno==EAGAIN)
- continue;
- exit(1);
- }
- print(id);
- lock_it.sem_num=0;
- lock_it.sem_op=1;
- lock_it.sem_flg=IPC_NOWAIT;
- if((semop(id,&lock_it,1))==-1)
- {
- perror(“semop2”);
- exit(1);
- }
- else
- {
- printf(“I’m finished,my pid is %d\n”,getpid());
- return;
- }
- }
- }
- sleep(3);
- semctl(id,0,IPC_RMID,0);
- exit(0);
- }
- }
- void print(int id)
- {
- printf(“I get id,my pid is %d\n”,getpid());
- value=semctl(id,0,GETVAL);
- printf(“now the value have %d\n”,value);
- sleep(1);
- }
复制代码
[ 本帖最后由 湖光倒影 于 2007-4-22 17:21 编辑 ] |
|