1.父子进程对话
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
int pfd[2];
int pfe[2];
if(pipe(pfd)<0)
{
perror("pipe");
return -1;
}
printf("创建管道成功 pfd[0]=%d pfd[1]=%d %d\n",pfd[0],pfd[1],__LINE__);
if(pipe(pfe)<0)
{
perror("pipe");
return -1;
}
printf("创建管道成功 pfe[0]=%d pfe[1]=%d %d\n",pfe[0],pfe[1],__LINE__);
pid_t pid=fork();
//父
if(pid>0)
{
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
read(pfe[0],buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
break;
printf("%s\n",buf);
bzero(buf,sizeof(buf));
scanf("%s",buf);
getchar();
if(write(pfd[1],buf,sizeof(buf))<0)
{
perror("write");
return -1;
}
if(strcmp(buf,"quit")==0)
break;
}
}
//子
else if(0==pid)
{
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
scanf("%s",buf);
getchar();
write(pfe[1],buf,sizeof(buf));
if(strcmp(buf,"qiut")==0)
break;
bzero(buf,sizeof(buf));
read(pfd[0],buf,sizeof(buf));
printf("%s\n",buf);
if(strcmp(buf,"quit")==0)
break;
}
}
else
{
perror("fork");
return -1;
}
close(pfd[0]);
close(pfd[1]);
close(pfe[0]);
close(pfe[1]);
return 0;
}
2.三线程分别打印ABC,打印顺序必须是ABC
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <sys/wait.h>
9 #include <pthread.h>
10 pthread_mutex_t mutex;
11 pthread_cond_t cond1;
12 pthread_cond_t cond2;
13 pthread_cond_t cond3;
14 int flag = 1;
15 void *callback1(void *arg)
16 {
17 while (1)
18 {
19 pthread_mutex_lock(&mutex);
20 if (flag != 1)
21 {
22 pthread_cond_wait(&cond3, &mutex);
23 }
24 printf("A");
25 flag = 2;
26 pthread_cond_signal(&cond1);
27 pthread_mutex_unlock(&mutex);
28 }
29 }
30 void *callback2(void *arg)
31 {
32 while (1)
33 {
34 pthread_mutex_lock(&mutex);
35 if (flag != 2)
36 {
37 pthread_cond_wait(&cond1, &mutex);
38 }
39 printf("B");
40 flag = 3;
41 pthread_cond_signal(&cond2);
42 pthread_mutex_unlock(&mutex);
43 }
44 }
45 void *callback3(void *arg)
46 {
47 while (1)
48 {
49 pthread_mutex_lock(&mutex);
50 if (flag != 3)
51 {
52 pthread_cond_wait(&cond2, &mutex);
53 }
54 printf("C\n");
55 flag = 1;
56 pthread_cond_signal(&cond3);
57 pthread_mutex_unlock(&mutex);
58 }
59 }
60 int main(int argc, const char *argv[])
61 {
62 pthread_mutex_init(&mutex, NULL);
63 pthread_cond_init(&cond1, NULL);
64 pthread_cond_init(&cond2, NULL);
65 pthread_cond_init(&cond3, NULL);
66 pthread_t tid1, tid2, tid3;
67 pthread_create(&tid1, NULL, callback1, NULL);
68 pthread_create(&tid2, NULL, callback2, NULL);
69 pthread_create(&tid3, NULL, callback3, NULL);
70 pthread_join(tid1, NULL);
71 return 0;
72 }
~
~
~
~
~
~
~
~
~
~
~