Linux下的多进程间共享资源的互斥访问
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Linux下的多进程间共享资源的互斥访问,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2302字,纯文字阅读大概需要4分钟。
内容图文
![Linux下的多进程间共享资源的互斥访问](/upload/InfoBanner/zyjiaocheng/972/b1150a5a0bc144b7a0627db5d340457b.jpg)
#include??? <stdio.h>? #include??? <stdlib.h>? #include??? <unistd.h>? #include??? <fcntl.h>? #include??? <sys/mman.h>? #include??? <pthread.h>? pthread_mutex_t* g_mutex;? //创建共享的mutex? void init_mutex(void)? {? ??? int ret;? ??? //g_mutex一定要是进程间可以共享的,否则无法达到进程间互斥? ??? g_mutex=(pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);? ??? if( MAP_FAILED==g_mutex )? ??? {? ??????? perror("mmap");? ??????? exit(1);? ??? }? ????? ??? //设置attr的属性? ??? pthread_mutexattr_t attr;? ??? pthread_mutexattr_init(&attr);? ??? //一定要设置为PTHREAD_PROCESS_SHARED? ??? //具体可以参考http://blog.chinaunix.net/u/22935/showart_340408.html? ??? ret=pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);? ??? if( ret!=0 )? ??? {? ??????? perror("init_mutex pthread_mutexattr_setpshared");? ??????? exit(1);? ??? }? ??? pthread_mutex_init(g_mutex, &attr);? }? int main(int argc, char *argv[])? {? ??? init_mutex();? ??? int ret;????? ??? char str1[]="this is child process/r/n";? ??? char str2[]="this is father process/r/n";? ??? int fd=open("tmp", O_RDWR|O_CREAT|O_TRUNC, 0666);? ??? if( -1==fd )? ??? {? ??????? perror("open");? ??????? exit(1);? ??? }? ??? pid_t pid;? ??? pid=fork();? ??? if( pid<0 )? ??? {? ??????? perror("fork");? ??????? exit(1);? ??? }? ??? else if( 0==pid )? ??? {? ??????? ret=pthread_mutex_lock(g_mutex);? ??????? if( ret!=0 )? ??????? {? ??????????? perror("child pthread_mutex_lock");? ??????? }? ??????? sleep(10);//测试是否能够阻止父进程的写入? ??????? write(fd, str1, sizeof(str1));? ??????? ret=pthread_mutex_unlock(g_mutex);??? ??????? if( ret!=0 )? ??????? {? ??????????? perror("child pthread_mutex_unlock");? ??????? }???? ??? }? ??? else? ??? {? ??????? sleep(2);//保证子进程先执行?? ??????? ret=pthread_mutex_lock(g_mutex);? ??????? if( ret!=0 )? ??????? {? ??????????? perror("father pthread_mutex_lock");? ??????? }? ??????? write(fd, str2, sizeof(str2));? ??????? ret=pthread_mutex_unlock(g_mutex);??? ??????? if( ret!=0 )? ??????? {? ??????????? perror("father pthread_mutex_unlock");? ??????? }???????????????? ??? }? ??? wait(NULL);? ??? munmap(g_mutex, sizeof(pthread_mutex_t));? }?
运行后tmp文件内容为:
this is child process
this is father process
???????????
内容总结
以上是互联网集市为您收集整理的Linux下的多进程间共享资源的互斥访问全部内容,希望文章能够帮你解决Linux下的多进程间共享资源的互斥访问所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。