#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int pfd[2];
int pfd2[2];
if(pipe(pfd)<0){
perror(“pipe”);
return -1;
}
if(pipe(pfd2)<0){
perror(“pipe”);
return -1;
}
pid_t pid=fork();
int i=1;
int n=0;
if(pid>0){//父进程为真
char buf[255];
char buf1[128];
ssize_t res;
while(1){
printf(“父进程写入\n”);
scanf(“%s”,buf);
getchar();
if(write(pfd[1],buf,sizeof(buf))<0){
perror(“write”);
return-1;
}
printf(“父写入完成\n”);
sleep(6);
// break;
printf(“父进程读取\n”);
bzero(buf1,sizeof(buf1));
bzero(buf,sizeof(buf));
res=read(pfd2[0],buf1,sizeof(buf1));
if(res<0){
perror(“read”);
return-1;
}
printf(“父进程读取:res=%ld buf=%s\n”,res,buf1);
if(strcmp(buf1,“quit”)==0){
break;
}
printf(“父读取完成\n”);
}
wait(NULL);
}else if(0==pid){
sleep(3);
char buf[128];
char buf1[128];
ssize_t res;
while(1){
sleep(3);
printf("子进程读取\n");
bzero(buf,sizeof(buf));
bzero(buf1,sizeof(buf1));
res=read(pfd[0],buf,sizeof(buf));
if(res<0){
perror("read");
return-1;
}
printf("子进程读取:res=%ld buf=%s\n",res,buf);
if(strcmp(buf,"quit")==0){
break;
}
printf("子读取完成\n");
printf("子进程写入\n");
scanf("%s",buf1);
getchar();
if(write(pfd2[1],buf1,sizeof(buf1))<0){
perror("write");
return-1;
}
printf("子进程写入完成\n");
}
exit(1);
}else{
perror("fork");
return-1;
}
close(pfd[0]);
close(pfd[1]);
return 0;
}
#include <stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<semaphore.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int flag=0;
void* aa(void*a){
while(1){
pthread_mutex_lock(&mutex);
if(flag!=0){
pthread_cond_wait(&cond,&mutex);
}
printf("A\n");
sleep(1);
flag=1;
pthread_cond_signal(&cond);
//printf("随机唤醒一个\n");
pthread_mutex_unlock(&mutex);
}
}
voidbb(voida){
while(1){
pthread_mutex_lock(&mutex);
if(flag!=1){
pthread_cond_wait(&cond,&mutex);
}
printf("C\n");
sleep(1);
flag=2;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
voidcc(voida){
while(1){
pthread_mutex_lock(&mutex);
if(flag!=2){
pthread_cond_wait(&cond,&mutex);
}
printf("B\n");
sleep(1);
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,aa,NULL)!=0){
return -1;
}
if(pthread_create(&tid2,NULL,bb,NULL)!=0){
return -1;
}
if(pthread_create(&tid3,NULL,cc,NULL)!=0){
return -1;
}
//pthread_detach(tid1);//分离tid1线程,分离后join不阻塞
//pthread_detach(tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);//阻塞,防止主线程退出,等到tid2线程退出后解除阻塞
pthread_mutex_destroy(&mutex);//销毁锁
pthread_cond_destroy(&cond);//销毁条件变量
return 0;
}