1>使用有名管道,完成两个进程的相互通信
//create.c
#include<myhead.h>int main(int argc, const char *argv[])
{if((mkfifo("myfifo1",0664))== -1){perror("mkfifo");return -1;}if((mkfifo("myfifo2",0664))== -1){perror("mkfifo");return -1;}getchar();system("rm myfifo1");system("rm myfifo2");return 0;
}
//01file.c
#include<myhead.h>void* write_file(void* arg)
{int wfd;//打开管道if((wfd = open("./myfifo1",O_WRONLY)) == -1){perror("open");exit(1);}char buf[128]="";while(1){printf("请写入:");fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1]=0;write(wfd,buf,sizeof(buf));if(strcmp(buf,"quit")==0){break;//exit(0);}}close(wfd);//pthread_exit(NULL);
}
void* read_file(void* arg)
{int rfd;if((rfd = open("./myfifo2",O_RDONLY)) == -1){perror("open");exit(1);}char buf[128]="";while(1){bzero(buf,sizeof(buf));read(rfd,buf,sizeof(buf));printf("输出的是%s\n",buf);if(strcmp(buf,"quit")==0){break;}}close(rfd);pthread_exit(NULL);}int main(int argc, const char *argv[])
{//创建线程pthread_t wtid = -1;//pthread_t rtid = -1;if(pthread_create(&wtid,NULL,write_file,NULL) != 0){perror("pthread_t");return -1;}if(pthread_create(&rtid,NULL,read_file,NULL) != 0){perror("pthread_t");return -1;}//回收线程pthread_join(rtid,NULL);pthread_join(wtid,NULL);return 0;
}
//02file.c
#include<myhead.h>
void* write_file(void* arg)
{int wfd;if((wfd = open("./myfifo2",O_WRONLY)) == -1){perror("open");exit(1);}char buf[128]="";while(1){printf("请写入:");fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1]=0;write(wfd,buf,sizeof(buf));if(strcmp(buf,"quit")==0){break;//exit(0);}}close(wfd);//pthread_exit(NULL);
}
void* read_file(void* arg)
{int rfd; if((rfd = open("./myfifo1",O_RDONLY)) == -1){perror("open");exit(1);}char buf[128]="";while(1){bzero(buf,sizeof(buf));read(rfd,buf,sizeof(buf));printf("输出的是%s\n",buf);if(strcmp(buf,"quit")==0){break;}}close(rfd);pthread_exit(NULL);}
int main(int argc, const char *argv[])
{//打开管道//创建线程pthread_t wtid = -1;//pthread_t rtid = -1;if(pthread_create(&wtid,NULL,write_file,NULL) != 0){perror("pthread_t");return -1;}if(pthread_create(&rtid,NULL,read_file,NULL) != 0){perror("pthread_t");return -1;}//回收线程pthread_join(rtid,NULL);pthread_join(wtid,NULL);return 0;
}