IPC之System V 信号量(后续代码实现)
来源:互联网 发布:逆袭 网络剧 在线1 编辑:程序博客网 时间:2024/06/05 04:49
上篇概括了system V信号量基本使用,下面自己实现的一个简单的信号量代码:
#include <sys/sem.h>#include <sys/ipc.h>#include <unistd.h>#include <time.h>#include <stdio.h>union semun {int val;struct semid_ds *buf;short *array;};void child1(int semid);void child2(int semid);int main(){ int ret; pid_t pid1,pid2; int semid1,semid2; struct sembuf sem; union semun sem_val; if((semid1 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){ perror("semget semid1 error!\n"); } if((semid2 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){perror("semget semid2 erroe!\n"); } sem_val.val = 0; ret = semctl(semid1,0,SETVAL,sem_val); if(ret < 0){perror("semctl1 error!\n"); } ret = semctl(semid2,0,SETVAL,sem_val); if(ret < 0){perror("semctl2 error!\n"); } pid1 = fork(); if(pid1 < 0){perror("fork pid1 error\n"); } else if(pid1 == 0){child1(semid1); } pid2 = fork(); if(pid2 < 0){perror("fork pid2 error\n"); } else if(pid2 == 0){child2(semid2); } sem.sem_num = 0; sem.sem_op = 1; sem.sem_flg = SEM_UNDO; while(1) {sleep(1);if(semop(semid1,&sem,1) == -1){ perror("semop semid1\n");}if(semop(semid2,&sem,1) == -1){ perror("semop semid2\n");} } return 0;}void child1(int semid1){ struct sembuf sem1; sem1.sem_num = 0; sem1.sem_op = -1; sem1.sem_flg = SEM_UNDO; while(1) {if(semop(semid1,&sem1,1) == -1){ perror("semop semid1\n");}printf("this is the child1\n");sleep(1); }}void child2(int semid2){ struct sembuf sem2; sem2.sem_num = 0; sem2.sem_op = -5; sem2.sem_flg = SEM_UNDO; while(1) {if(semop(semid2,&sem2,1) == -1){ perror("semop semid2\n");}printf("this is the child2\n");sleep(1); }}
运行结果如下:this is the child1this is the child1this is the child1this is the child1this is the child1this is the child2this is the child1this is the child1this is the child1this is the child1this is the child1this is the child2本文仅限学习之用,如有雷同不胜荣幸!!有误之处请指出,谢谢合作!
- IPC之System V 信号量(后续代码实现)
- IPC之System V 消息队列 (代码实现)
- IPC笔记之System V信号量
- 【记录】system v ipc(3) 信号量
- 信号量/灯(system V IPC)
- Linux ipc------System V信号量
- 【C语言】【unix c】信号量集(system v ipc)
- SYSTEM V IPC——信号量笔记
- Linux IPC实践 --System V信号量(1)
- Linux IPC实践--System V信号量(2)
- 信号量(System V)
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- linux基础编程:进程通信之System V IPC:消息队列,信号量,共享内存
- linux基础编程:进程通信之System V IPC:消息队列,信号量,共享内存
- System V信号量(1)
- System V信号量(2)
- System V信号量(3)
- OpenGL基础知识(四)
- 一、进程管理
- Hibernate用到的CommonDao(包括分页)
- Hibernate常用的BaseDao
- 10g RAC改归档模式步骤
- IPC之System V 信号量(后续代码实现)
- ext.grid的配置属性和方法
- jetty线程池的实现
- ubuntu下安装Apache+PHP+Mysql
- extjs4 combobox学习之可以用来查询的combo
- Spring Form Tags
- 利用Squid搭建透明代理网关服务器
- csdn太不给力了
- Fedora 15 SSH安装与配置