raybin_yang 发表于 2012-11-07 23:58

求解信号量互斥的问题

{:3_199:} 这几天在看Linux下进程相关的内容,试了试信号量,想让两个进程互斥运行,可是看打印出来的log,感觉两个进程是交替进行的。。我郁闷不解,代码如下:#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/mman.h>

int main()
{
    int count;
    sem_t mutex;
    struct sched_param param;
    int prio;
    if(sem_init(&mutex,1,1) < 0)
    {
      printf("init fail\n");
    }

    printf("%d\n",sched_getscheduler(0));

    if(fork()==0)
    {
      prio = sched_get_priority_min(SCHED_FIFO);
      param.sched_priority = prio;
      if (sched_setscheduler(0, SCHED_FIFO, &param) == -1)
      {
            printf("Child Error\n");
      }
      sleep(5);
      sem_wait(&mutex);
      printf("child %d\n",sched_getscheduler(0));
      for(count=0;count < 10;count++)
      {
            printf("step %d in child\n",count);
            sleep(1);
      }
      sem_post(&mutex);
      exit(0);
    }
    else
    {
      prio = sched_get_priority_max(SCHED_FIFO);
      param.sched_priority = prio;
      if (sched_setscheduler(0, SCHED_FIFO, &param) == -1)
      {
            printf("Father Error\n");
      }
      sleep(10);
      sem_wait(&mutex);
      printf("father %d\n",sched_getscheduler(0));
      for(count=0;count < 10;count++)
      {
            printf("step %d in father\n",count);
      }
      sem_post(&mutex);
      exit(0);
    }
}
结果输入的结果是这样的:0
child 1
step 0 in child
step 1 in child
step 2 in child
step 3 in child
step 4 in child
father 1
step 0 in father
step 1 in father
step 2 in father
step 3 in father
step 4 in father
step 5 in father
step 6 in father
step 7 in father
step 8 in father
step 9 in father
step 5 in child
step 6 in child
step 7 in child
step 8 in child
step 9 in child
怎样才能做到互斥访问的。。。求解{:3_196:}

buzz-lin 发表于 2012-11-08 16:21

是因为    sem_t mutex 这个变量不是在共享内存中,这个变量在产生子进程后 父子进程中个有一个所以当你对信号灯操作时实际上是各操作个的   
这种基于内存的信号灯一定要在共享内存中
办法就是就把信号灯放在共享内存中 这样父子进程就只有一份啦用mmap分配一块
11行   sem_t mutex;
改为
sem_t * mutex=(sem_t *) mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
当然要检查mutex分配成功没有我这里就省略了把下面的几个&mutex改为 mutex就好了

raybin_yang 发表于 2012-11-08 21:57

回复 2# buzz-lin


   {:3_199:}我原本以为无名信号量是可以在进程内共享了。。好像不行,后来我用线程间的互斥量了~THX~

linux_c_py_php 发表于 2012-11-10 00:46

进程间共享要么是system v的IPC, 要么是在共享内存里初始化sem, 那么进程只要打开共享内存就可以直接使用sem了.

但sem本身就是可以用有名的跨进程, 所以没必要折腾.

raybin_yang 发表于 2012-11-10 11:00

回复 4# linux_c_py_php


   {:3_186:}在学Linux编程的新手{:3_199:}好多内容。。
页: [1]
查看完整版本: 求解信号量互斥的问题