信息量编程
程序员文章站
2024-03-19 18:39:52
...
1.#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//int semget(key_t key, int nsems, int semflg);
//int semctl(int semid, int semnum, int cmd, ...);
union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
int main()
{
key_t key;
int semid;
key = ftok(".",1);
semid = semget(key,1,IPC_CREAT|0666);
union semun initsem;
initsem.val = 1;
semctl(semid,0,SETVAL,initsem);//
int pid = fork();
if(pid>0) {
printf("this is father\n");
} else if(pid == 0) {
printf("this is child\n");
} else {
printf("fork error\n");
}
return 0;
}
2.终极信号量编程
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//int semget(key_t key, int nsems, int semflg);
//int semop(int semid, struct sembuf *sops, size_t nsops);
//int semctl(int semid, int semnum, int cmd, ...);
union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
void pGetkey(int id)
{
struct sembuf set;
set.sem_num = 0;
set.sem_op = -1;
set.sem_flg = SEM_UNDO;
semop(id,&set,1);
printf(“getkey\n”);
}
void vPutBackkey(int id)
{
struct sembuf set;
set.sem_num = 0;
set.sem_op = 1;
set.sem_flg = SEM_UNDO;
semop(id,&set,1);
printf(“putbackkey\n”);
}
int main()
{
key_t key;
int semid;
key = ftok(".",1);
semid = semget(key,1,IPC_CREAT|0666);
union semun initsem;
initsem.val = 0;
semctl(semid,0,SETVAL,initsem);//
int pid = fork();
if(pid>0) {
pGetkey(semid);
printf("this is father\n");
vPutBackkey(semid);
semctl(semid,0,IPC_RMID ); //销毁
} else if(pid == 0) {
printf("this is child\n");
vPutBackkey(semid);
} else {
printf("fork error\n");
}
return 0;
}
上一篇: RUNOOB python练习题29
推荐阅读
-
信息量编程
-
【Unity】【C#】《U3d人工智能编程精粹》学习心得--------AI角色的感知方式-视觉感知实现解读
-
如何高效又快速的学会一门编程语言
-
如何学习编程、一门编程语言怎么算入门、快速掌握一门编程语言
-
Linux编程之有限状态机FSM的理解与实现
-
软件工程中的经济行为与软件架构师的工作 博客分类: 架构乱弹 工作软件测试敏捷开发项目管理编程
-
Hadoop 博客分类: java HadoopMapreducelucene编程搜索引擎
-
软件工程中的经济行为与软件架构师的工作 博客分类: 架构乱弹 工作软件测试敏捷开发项目管理编程
-
Linux下MapReduce编程之数据去重
-
04-java并发编程之定时线程池ScheduledThreadPoolExecutor