两个有名管道实现qq通信

来源:互联网 发布:女鬼墨捏脸数据 编辑:程序博客网 时间:2024/06/01 09:17

1.先创建两个有名管道:

/* ============================================================================ Name        : qqConnext.c Author      :  Version     : Copyright   : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */#include <stdio.h>#include <stdlib.h>#include<sys/stat.h>#include<sys/types.h>#include<fcntl.h>int main(int argc,char **argv){if(mkfifo("rdfifo",0666)<0){perror("create pipe wrong!");exit(1);}if(mkfifo("wrfifo",0666)<0){perror("create pipe wrong!");exit(1);}return EXIT_SUCCESS;}

2.client端:一共两个进程,一个用来读,一个用来写

#include <stdio.h>#include <stdlib.h>#include<sys/stat.h>#include<sys/types.h>#include<fcntl.h>#include<string.h>#include<unistd.h>int main(){pid_t pid;int rfd,wfd;char buf[1024];int len;umask(0);while((rfd=open("wrfifo",O_RDONLY))==-1);wfd=open("rdfifo",O_RDWR);if(wfd==-1){perror("client write wrong");}pid=fork();if(pid==0){while(1){printf("client:");fgets(buf,1024,stdin);buf[strlen(buf)-1]='\0';   if(strcmp(buf,"quit")==0){close(rfd);unlink("rdfifo");   exit(0);}write(wfd,buf,strlen(buf));}}else{while(1){len=read(rfd,buf,1024);if(len==-1){perror("client read wrong");}else{    buf[len]='\0';printf("server:%s\n",buf);}}}exit(0);}

3.server端:

#include <stdio.h>#include <stdlib.h>#include<sys/stat.h>#include<sys/types.h>#include<fcntl.h>#include<string.h>#include<unistd.h>int main(int argc,char **argv){    pid_t pid;    int wfd,rfd;    char buf[1024];    int len;    wfd=open("wrfifo",O_RDWR);    umask(0);    if(wfd==-1)    {        perror("open pipe wrfifo wrong!");        exit(1);    }    while((rfd=open("rdfifo",O_RDONLY))==-1)    {    }    pid=fork();    if(pid==0)    {        while(1)        {        len=read(rfd,buf,1024);        if(len==-1)        {            perror("server write wrong");            exit(1);        }        else        {            buf[len]='\0';            printf("Client:%s\n",buf);        }        }    }    else if(pid>0)    {       while(1)        {           printf("server:");            fgets(buf,1024,stdin);//从标准输入获取            buf[strlen(buf)-1]='\0';            if(strcmp(buf,"q")==0)            {                close(wfd);                unlink("wrfifo");                exit(0);            }            write(wfd,buf,strlen(buf));        }    }    exit(0);}



原创粉丝点击