2013-03-21 46 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