一、使用有名管道实现两个进程之间的相互通信
代码如下:
创建有名管道文件
#include <myhead.h> int main(int argc, const char *argv[]) {if(mkfifo("myfifo",0664)==-1){perror("create error");return -1;}if(mkfifo("myfifo_1",0664)==-1){perror("create error");return -1;}getchar();unlink("myfifo");unlink("myfifo_1");return 0; }
进程A通信
#include <myhead.h> sem_t sem; void* task(void *arg) {sem_wait(&sem); // printf("subthread A\n");int rfd=open("myfifo_1",O_RDONLY);if(rfd==-1){perror("open error");return NULL;}char rbuf[128]="";while(1){bzero(rbuf,sizeof(rbuf));read(rfd,rbuf,sizeof(rbuf));printf("\n接收到信息:%s\n",rbuf);if(strcmp(rbuf,"bye")==0)break;}pthread_exit(NULL); } int main(int argc, const char *argv[]) {sem_init(&sem,0,0);pthread_t tid=-1;if(pthread_create(&tid,NULL,task,NULL)!=0){printf("create error\n");return -1;}printf("main thread A\n");int wfd = open("myfifo",O_WRONLY);if(wfd==-1){perror("open error");return -1;}//向管道中写入文件char wbuf[128]="";while(1){bzero(wbuf,sizeof(wbuf));printf("请输入:");fgets(wbuf,sizeof(wbuf),stdin);wbuf[strlen(wbuf)-1]=0;//写入管道write(wfd,wbuf,sizeof(wbuf));printf("发送成功\n");sem_post(&sem);if(strcmp(wbuf,"bye")==0)break;}close(wfd);pthread_join(tid,NULL);sem_destroy(&sem);return 0; }
进程B通信功能
#include <myhead.h> sem_t sem; void* task(void *arg) {sem_wait(&sem); // printf("subthread\n");int wfd=open("myfifo_1",O_WRONLY);if(wfd==-1){perror("open error");return NULL;}char wbuf[128]="";while(1){bzero(wbuf,sizeof(wbuf));printf("请回答:");fgets(wbuf,sizeof(wbuf),stdin);wbuf[strlen(wbuf)-1]=0;write(wfd,wbuf,sizeof(wbuf));printf("发送成功\n");if(strcmp(wbuf,"bye")==0)break;}pthread_exit(NULL); } int main(int argc, const char *argv[]) {pthread_t tid=-1;sem_init(&sem,0,0);if(pthread_create(&tid,NULL,task,NULL)!=0){printf("create error");return -1;}printf("main thread\n");int rfd=open("myfifo",O_RDONLY);if(rfd==-1){perror("open error");return -1;}char rbuf[128]="";while(1){bzero(rbuf,sizeof(rbuf));read(rfd,rbuf,sizeof(rbuf));printf("\n接收到的信息:%s\n",rbuf);sem_post(&sem);if(strcmp(rbuf,"bye")==0)break;}close(rfd);pthread_join(tid,NULL);sem_destroy(&sem);return 0; }
二、思维导图