免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6302 | 回复: 5
打印 上一主题 下一主题

semaphore,sem_init的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-05-14 05:07 |只看该作者 |倒序浏览
命名的semaphore基本会用,但是想在父子进程间用匿名的semaphore,用了这个sem_init,但是没起作用。估计是我没理解对这个东西。请懂的朋友赐教。

我是想父进程scanf等待输入的时候,子进程不会一直打印1,2; 而子进程打印1,2的过程中,父进程不会让你input。
  1. int main(int argc, char** argv){
  2.         sem_t mutex;
  3.         sem_init(&mutex, 1, 1);
  4.         char buffer[100];
  5.         pid_t pid;
  6.         pid = fork();
  7.         if(pid == 0){
  8.                 while(1){
  9.                         sem_wait(&mutex);
  10.                         printf("1\n");
  11.                         sleep(1);
  12.                         printf("2\n");
  13.                         sem_post(&mutex);
  14.                 }
  15.         }
  16.         else{
  17.                 while(1){
  18.                         sem_wait(&mutex);
  19.                         printf("input:");
  20.                         scanf("%s",buffer);
  21.                         sem_post(&mutex);
  22.                 }
  23.         }
  24. }
复制代码
运行的结果是,父子进程依然各干各的事,没有互相等待。

论坛徽章:
0
2 [报告]
发表于 2011-05-14 08:31 |只看该作者
sem_init的man page里有一段话,不知道与这个问题是否有关?

       sem_init initializes the semaphore object pointed to by sem.  The count
       associated  with  the semaphore is set initially to value.  The pshared
       argument indicates whether the semaphore is local to the  current  pro-
       cess  ( pshared is zero) or is to be shared between several processes (
       pshared is not zero). LinuxThreads currently does not support  process-
       shared  semaphores
,  thus  sem_init always returns with error ENOSYS if
       pshared is not zero.

论坛徽章:
0
3 [报告]
发表于 2011-05-15 03:10 |只看该作者
关注,来学习

论坛徽章:
0
4 [报告]
发表于 2011-05-16 13:07 |只看该作者
这个你需要了解下fork时对POSIX unnamed semaphores.如果你的匿名信号量是在共享内存(比如匿名映射所创建的共享内存)中,那这个匿名信号量会被父子进程共享,否则的话子进程会拷贝一份匿名信号量。也就是说你的父子进程中所操作的根本不是同一个匿名信号量,所以你这样是不行的

论坛徽章:
0
5 [报告]
发表于 2011-05-18 18:08 |只看该作者
shm_open共享内存我知道,那请问如果能把这个semaphore放在共享内存区呢?

论坛徽章:
0
6 [报告]
发表于 2011-05-19 11:09 |只看该作者
我没试过,大概下面这意思吧

  1. sem_t *sem;
  2. ...
  3. sem = (sem_t *)mmap(NULL, sizeof(sem_t), ...)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP