在下面的代码中,难道不会在子进程中创建一个互斥锁作为其父进程的副本吗?因此,现在有两个互斥锁的副本--一个在子进程中,一个在父进程中。如何进行同步?据我所知,您需要一个由多个进程共享的副本才能使其同步。
#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);
}发布于 2013-03-22 04:56:56
您不能将mutex与semaphore混淆。一个semaphore可能允许多个线程/进程访问一个资源,一个mutex只允许一个并发访问一个资源。
正如here所述,您需要创建一个named semaphore来使跨进程同步成为可能。您必须在父进程中创建semaphore,并且access在子进程中使用sem_open来实现同步。
https://stackoverflow.com/questions/15557773
复制相似问题