2.编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,
要求输出结果必须按ABC的顺序显示,如ABCABC.... .依次递推
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1,sem2,sem3;
void *callBack_A(void *arg)
{
int i=10;
while(i--){
sem_wait(&sem1);
printf("A");
fflush(stdout);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *callBack_B(void *arg)
{
int i=10;
while(i--){
sem_wait(&sem2);
printf("B");
fflush(stdout);
sem_post(&sem3);
}
pthread_exit(NULL);
}
void *callBack_C(void *arg)
{
int i=10;
while(i--){
sem_wait(&sem3);
printf("C");
fflush(stdout);
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem1,0,1)!=0){
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)!=0){
perror("sem_init");
return -1;
}
if(sem_init(&sem3,0,0)!=0){
perror("sem_init");
return -1;
}
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,callBack_A,NULL)!=0){
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,callBack_B,NULL)!=0){
perror("pthread_create");
return -1;
}
if(pthread_create(&tid3,NULL,callBack_C,NULL)!=0){
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
return 0;
}
创建父子进程,实现父子进程的通话。
1)父进程先发送句话给子进程,子进程接收打印。
2)子进程发送与句话给父进程,父进程接收后打印。
3)重复1) 2)步骤即可。
4)当父进程或者子进程发送quit后,父子进程均要结束。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int pfd[2]={0};
if(pipe(pfd)<0){
perror("pipe");
return -1;
}
int pfd1[2]={0};
if(pipe(pfd1)<0){
perror("pipe");
return -1;
}
char buf[128]="";
ssize_t res=0;
pid_t pid=fork();
if(pid>0){
close(pfd[0]);
close(pfd1[1]);
while(1){
bzero(buf,sizeof(buf));
printf("请在父进程输入要传给子进程的话:");
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if(strcmp("quit",buf)==0)
break;
res=write(pfd[1],buf,sizeof(buf));
if(res<0){
perror("write");
return -1;
}
else if(0==res)
break;
bzero(buf,sizeof(buf));
res=read(pfd1[0],buf,sizeof(buf));
if(res<0){
perror("read");
return -1;
}
else if(0==res)
break;
if(strcmp("quit",buf)==0)
break;
printf("父进程接受成功%s\n",buf);
fflush(stdout);
}
close(pfd[1]);
close(pfd1[0]);
}
else if(0==pid){
close(pfd[1]);
close(pfd1[0]);
while(1){
bzero(buf,sizeof(buf));
res=read(pfd[0],buf,sizeof(buf));
if(res<0){
perror("read");
return -1;
}
else if(res==0)
break;
if(strcmp("quit",buf)==0)
break;
printf("子进程接受成功%s\n",buf);
bzero(buf,sizeof(buf));
printf("请在子进程输入要传给父进程的话:");
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if(strcmp("quit",buf)==0){
break;
}
res=write(pfd1[1],buf,sizeof(buf));
if(res<0){
perror("write");
return -1;
}
else if(0==res)
break;
}
close(pfd[0]);
close(pfd1[1]);
}
else{
perror("fork");
return -1;
}
close(pfd[0]);
close(pfd1[1]);
return 0;
}