展开全部
/***********
编程实现 进程的同步与互斥
题目:有父亲/儿子/女儿三人和一个盘子.
当盘子为空的时候,父亲 随机往盘子里放香蕉或苹果;
儿子和女儿马上取该水果,但儿子只拿苹果,女儿只拿香蕉
父亲共放20次.
编程模拟实现!
*************/
#include<stdio.h>
#include <errno.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
//#include <process.h>//for windows
#define OPEN_FLAG O_RDWR|O_CREAT
#define OPEN_MODE 00777
#define INIT_V 0
static sem_t *sem_apple = NULL;
static sem_t *sem_banana = NULL;
int fatherdo(){
int i=20;
while(i-->0){
printf("[%u]father put %s \n",i,i%2==0 ?"Apple":"Banana");
if(i%2==0){
sem_post(sem_apple);
}else{
sem_post(sem_banana);
}
sleep(1);
}
//删掉在系统创建的信号量
sem_unlink("sem_apple");
sem_unlink("sem_banana");
//彻底销毁打开的信号量
sem_close(sem_apple);
sem_close(sem_banana);
return 0;
}
int sondo(){
sleep(2);
int i=10;
while(i-->0){
//P操作
sem_wait(sem_apple);
printf("[%u]Son:I get an apple,father!\n\n",i);
}
return 0;
}
int daughterdo(){
sleep(2);
int i=10;
while(i-->0){
//P操作
sem_wait(sem_banana);
printf("[%u]Daughter:I get an bnana,father!\n\n",i);
}
return 0;
}
int main(){
printf("Program begin:\n\n");
//创建2个命名信号量
sem_apple = sem_open("sem_apple", OPEN_FLAG, OPEN_MODE, INIT_V);
sem_banana = sem_open("sem_banana", OPEN_FLAG, OPEN_MODE, INIT_V);
pid_t pid=-1;
pid=fork();
if(-1==pid){
perror("Failed fork()!");return 1;
}else if(pid==0){
//子进程 儿子
sondo();
}else if(pid>0){
pid=fork();
if(-1==pid){
perror("Failed fork()!");return 1;
}else if(pid==0){
//子进程女儿
daughterdo();
}else if(pid>0){
//主进程
fatherdo();
printf("Program End...\n\n");
}
}
printf("[%d <= %d]Three Process are end!\n",getpid(),getppid());
return 0;
}
进程 信号量通信 模式.
参考: http://blog.sina.com.cn/s/blog_510737a301012z7e.html
我一般都是 线程间通信的。进程间通信 不太熟悉,所以这才 试着写了写。
追问
这个在VB中有错啊,你运行出来了吗,可以把结果发给我看一下吗,谢谢
追答
这个 是C语言,C语言啊....
还用VB..... 当然可以运行了.
在 centos 2.6.32-220.el6.x86_64 [CentOS linux release 6.2 (Final)]
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
下正常运行.
运行结果:
root@VM_64_69_centos ~]$ nano test.cpp
[root@VM_64_69_centos ~]$ gcc test.cpp -lpthread
/tmp/cctqMZ4W.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld 返回 1
[root@VM_64_69_centos ~]$ g++ test.cpp -lpthread
[root@VM_64_69_centos ~]$ ./a.out
Program begin:
[19]father put Banana
[18]father put Apple
[9]Son:I get an apple,father!
[9]Daughter:I get an bnana,father!
[17]father put Banana
[8]Daughter:I get an bnana,father!
[16]father put Apple
[8]Son:I get an apple,father!
............
[1]father put Banana
[0]Daughter:I get an bnana,father!
[20256 <= 20254]Three Process are end!
[0]father put Apple
[0]Son:I get an apple,father!
[20255 <= 20254]Three Process are end!
Program End...
[20254 <= 20124]Three Process are end!
[root@VM_64_69_centos ~]$
不知道为什么,gcc编译 报错了...
g++正常.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询