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);
  }
4

1 回答 1

1

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

于 2013-03-21T20:56:56.380 回答