- 论坛徽章:
- 1
|
现有两个进程,它们之间要同时编程某一个文件,如何做到正确的进程之间的互斥呢?- #include <stdio.h>
- #include <stdlib.h>
- #include <error.h>
- #include <pthread.h>
- #include <sys/mman.h>
- #include <fcntl.h>
- #include <string.h>
- int main(int argc,char* argv[])
- {
- int fd;
- char dir[]="/simple.shm";
- pthread_mutex_t* lock;
- pthread_mutexattr_t mutexAttr;
- fd = shm_open(dir,O_RDWR,0777);
- /*not create yet*/
- if(fd == -1)
- {
- printf("Shared memory open<%s> failed!\n",dir);
- close(fd);
- fd = shm_open(dir,O_CREAT|O_TRUNC|O_RDWR,0777);
- if( -1 == fd )
- {
- printf("Shared memory create failed\n");
- return -1;
- }
- if(ftruncate(fd,sizeof(pthread_mutex_t)))
- {
- printf("Shared ftruncate failed\n");
- return -1;
- }
- lock = mmap(NULL,sizeof(pthread_mutex_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
- if(lock == MAP_FAILED)
- {
- printf("Shared MAP_FAILED\n");
- }
- close(fd);
- }
- else
- {
- lock = mmap(NULL,sizeof(pthread_mutex_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
- close(fd);
- }
- printf("Shared memory open<%s> sucess in process 1!\n",dir);
- pthread_mutexattr_init(&mutexAttr);
- pthread_mutexattr_setpshared(&mutexAttr,PTHREAD_PROCESS_SHARED);
- pthread_mutex_init(lock,&mutexAttr);
- /**以上是设置共享内存的pthread_mutex_t**/
- /*sys.log在当前目录初始不存在*/
- int syslog_fd;
- int i=0;
- while(i<5)
- {
- pthread_mutex_lock(lock);
- /*create sys.log*/
- syslog_fd = open("sys.log",O_CREAT|O_EXCL,0777);/*没有则创建*/
- if(-1 == syslog_fd)
- {
- printf("You never see this!\n");
- pthread_mutex_unlock(lock);
- return -1;
- }
- printf("open one time in process 1!.\n");
- sleep(2); /*我发现如果再这个点 ,启另外一个同样的进程B,会导致B打印You never see this! 我想在这个点锁应该是lock的啊 B进程为什么会进入open那里呢?*/
- remove("sys.log"); /*然后删除*/
- pthread_mutex_unlock(lock);
- sleep(2); /*如果在这个点 启同样的进程B,是没有问题的?*/
- i++;
- }
- return 0;
- }
复制代码 那么进程之间的互斥,找lock和unlock之间 sleep怎么会是这种情况呢?求赐教? |
|