具有进程的二进制信号量的通用模板

时间:2014-04-05 19:20:55

标签: linux operating-system semaphore

我正在学习信号量,并想在我之前实现的共享内存程序上尝试信号量IPC。 (该程序涉及在父进程和子进程之间共享共享内存:读取和写入等)。当我使用一个变量并在Parent中递增它并在child中递减它时,由于Race条件我得到意外的输出。所以我想用Semaphore同步这两个。但我需要一个起点,一个模板开始。 我使用这样的模板(初始化,附加,分离等)完成了以前的共享内存示例,我发现其他地方。所以,如果有人可以建议一些步骤......

我在尝试什么:

struct shmarea    // My shared Memory
{
  ` unsigned long count;
};    
struct shmarea *shma;

main()
{
  id =  shmget(KEY1,4096,IPC_CREAT|0600);
  shma = shmat(id,0,0); 
  shma->count = 0;
  ret = fork();

 if(ret>0)
 {    
 printf("in parent .. ppid is %lu ...and pid is %lu\n",getppid(),getpid()); 
 sleep(5);
 while(j++ < 2147483645){  // The large loop is to See the processes in top command
 while(i++ < 2147483645) shma->count++;   
     }

 }
 if(ret==0)
 {     
    printf("in child .. ppid is %lu ...and pid is %lu\n",getppid(),getpid());       
    while(j++ < 2147483645){
        while(i++ < 2147483645) shma->count--;
    }   
    exit(0); 
 }

 if(ret>0)
 {
    //Clean up
 }
}

我确实在寻找信号量创建示例。但主要是我坚持使用信号量集。如何用二进制信号量映射...因为在这个简单的程序中我只需要有两个值0和1。