1.父子进程对话
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <pthread.h>
int main(void)
{
int pfd1[2];
int pfd2[2];
pipe(pfd1);
pipe(pfd2);
pid_t pid=fork();
if(pid<0)
{
perror("fork");
return -1;
}
if(pid==0)
{
char buf[255]={0};
while (1)
{
memset(buf,0,sizeof(buf));
read(pfd1[0],buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
break;
printf("father:%s\n",buf);
memset(buf,0,sizeof(buf));
printf("子进程讲话:");
fscanf(stdin,"%s",buf);
write(pfd2[1],buf,strlen(buf));
if(strcmp(buf,"quit")==0)
break;
}
}
else
{
char buf[255]={0};
while (1)
{
memset(buf,0,sizeof(buf));
printf("你是父亲,你先说话:");
fscanf(stdin,"%s",buf);
write(pfd1[1],buf,strlen(buf));
if(strcmp(buf,"quit")==0)
break;
memset(buf,0,sizeof(buf));
read(pfd2[0],buf,sizeof(buf));
printf("son:%s\n",buf);
if(strcmp(buf,"quit")==0)
break;
}
wait(NULL);
}
close(pfd1[0]);
close(pfd2[0]);
close(pfd1[1]);
close(pfd2[1]);
return 0;
}
运行事例:
2.三线程分别打印ABC,打印顺序必须是ABC
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond1;
pthread_cond_t cond2;
pthread_cond_t cond3;
int flag = 1;
void *A(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
if (flag != 1)
{
pthread_cond_wait(&cond3, &mutex);
}
printf("A");
flag = 2;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
}
void *B(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
if (flag != 2)
{
pthread_cond_wait(&cond1, &mutex);
}
printf("B");
flag = 3;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
}
void *C(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
if (flag != 3)
{
pthread_cond_wait(&cond2, &mutex);
}
printf("C\n");
flag = 1;
pthread_cond_signal(&cond3);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond1, NULL);
pthread_cond_init(&cond2, NULL);
pthread_cond_init(&cond3, NULL);
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, A, NULL);
pthread_create(&tid2, NULL, B, NULL);
pthread_create(&tid3, NULL, C, NULL);
pthread_join(tid1, NULL);
return 0;
}
运行测试: