linux 下信号量

来源:百度文库 编辑:神马文学网 时间:2024/04/27 19:31:00

#include
#include
#include
#include
#include

union semun
{
int val;

struct semid_ds *buf;

unsigned short int *array;

struct seminfo *_buf;


};

 

int
main(void)
{

   key_t key;
  
   int proj_id=1;
  
   char * path_name="/home/informix/";//testSource/test";
  
   key=ftok(path_name,proj_id);
  
   if (key==-1)
{
   perror("创建IPC关键字错误");
    
   return -1;
  
}


    int semid;


semid=semget(key,1,IPC_CREAT|0777);

if (semid==-1)
{
  
  
   perror("创建信号量失败");
    
   return -2;
  
}
  


   union semun arg;
  
   arg.val=1;
  
   if (semctl(semid,0,SETVAL,arg)==-1)
   {
   
    perror("初始化信号量集失败");

return -3;   
   
   }

   pid_t child;
  
   int i;

   struct sembuf wait_singal,notify;

   wait_singal.sem_num=0;

   wait_singal.sem_op=-1;

   wait_singal.sem_flg=SEM_UNDO;
  
   notify.sem_num=0;

   notify.sem_op=1;

   notify.sem_flg=SEM_UNDO;

   pid_t pid_main=getpid();
  
   for (i=0;i<5;i++)
   {   
   child=fork();
  
   }
  

 

   /********************尝试进入临界区*******************/


   while(semop(semid,&wait_singal,1)==-1)
{
if (errno!=EINTR) return -4;
    
printf("进程在进入临界区信号中断,将重置");

}

   printf("进程: %d收到了信号灯上的信号\n",getpid());


   /*******************离开临界区***********************/

  
   while(semop(semid,¬ify,1)==-1)
   {
if (errno!=EINTR) return -5;

printf("进程在退出临界区信号中断,将重置");
   }
  
   printf("进程: %d在信号灯上发送了信号\n\n",getpid());

   if (!child) printf("父进程产生一个子进程\n",getpid());

   while(wait(NULL)!=-1);

   if (getpid()==pid_main)
   {
     printf("主进程的ID为:%d\n",pid_main);

if (semctl(semid,0,IPC_RMID,0)==-1)

     {
   perror("删除信号量错误");
   return -6;
     }
   }


   return 0;





}