兩個有名管道實現qq通訊

wzm10455發表於2013-01-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);
}



相關文章