2013-03-21 47 views
1

在下面的代码中,是不是将一个互斥量创建为子对象的副本?因此,现在有两个互斥量 - 一个在儿童中,一个在父母中。它如何同步?据我记得,你需要一个由多个进程共享的副本,以使其同步。信号量并发性

#include <semaphore.h> 
    #include <stdio.h> 
    #include <errno.h> 
    #include <stdlib.h> 
    #include <unistd.h> 
    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <fcntl.h> 
    #include <sys/mman.h> 

    int main(int argc, char **argv) 
    { 
    int fd, i,count=0,nloop=10,zero=0,*ptr; 
    sem_t mutex; 

    //open a file and map it into memory 

    fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU); 
    write(fd,&zero,sizeof(int)); 

    ptr = mmap(NULL,sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); 

    close(fd); 

    /* create, initialize semaphore */ 
    if(sem_init(&mutex,1,1) < 0) 
     { 
     perror("semaphore initilization"); 
     exit(0); 
     } 
    if (fork() == 0) { /* child process*/ 
     for (i = 0; i < nloop; i++) { 
     sem_wait(&mutex); 
     printf("child: %d\n", (*ptr)++); 
     sem_post(&mutex); 
     } 
     exit(0); 
    } 
    /* back to parent process */ 
    for (i = 0; i < nloop; i++) { 
     sem_wait(&mutex); 
     printf("parent: %d\n", (*ptr)++); 
     sem_post(&mutex); 
    } 
    exit(0); 
    } 
+1

http://stackoverflow.com/questions/8359322/how-to-share-semaphores-between-processes-using-shared-memory – 2013-03-21 20:57:36

回答

1

您不得将mutexsemaphore混淆。 A semaphore可能允许多个线程/进程访问资源,并且只允许ONE并发访问资源。
正如here所述,您需要创建一个named semaphore以使跨进程同步成为可能。 您必须在父进程中创建一个semaphore,并且在子进程中使用sem_open来实现同步。

+0

谢谢,我碰到上面的代码片断就一边学习同步,并怀疑是否它会工作。感谢您确认这一点,学习新事物感觉很好 – Daniel 2013-03-21 21:15:49

+2

不要忘记,如果命名信号量超出了程序的生命周期,除非它明确解除链接(或在命令行中删除)。否则,当你下一次运行你的程序时,会导致真正的地狱,因为信号量仍然存在于程序最后退出时留下的值。 – bazza 2013-03-22 08:14:22