下面两个仁兄总结非常好。

总结比较好:http://blog.csdn.net/wallwind/article/details/7212946

比较具体(例子):http://blog.csdn.net/monkey_d_meng/article/details/5628663



主要学习一个例子:

/*
 * test1.c
 *
 *  Created on: 2016年7月26日
 *      Author: Andy_Cong
 */

/*
 * 利用多线程与有名管道技术,
 * 实现两个进程之间发送即时消息,实现聊天功能。
 * */
//mkfifo xx  (新建一个管道xx)
//两个程序test1 test2 两个管道fofi1 fofi2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include<errno.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void *writefofi(void *arg)
{
	char *filename=(char *)arg;
	int fd=open(filename,O_WRONLY);
	if(fd==-1)
	{
		printf("open error is: %s\n",strerror(errno));
		return NULL;
	}
	char buf[1024];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		read(STDOUT_FILENO,buf,sizeof(buf));
		write(fd,buf,strlen(buf));
	}
	close(fd);
	return NULL;
}
void *readfofi(void *arg)
{
	char *filename = (char *) arg;
	int fd = open(filename, O_RDONLY);
	if (fd == -1)
	{
		printf("open error is: %s\n", strerror(errno));
		return NULL;
	}
	char buf[1024];
	while (1)
	{
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("%s",buf);
	}
	close(fd);
	return NULL;
}


int main(int argc,char *argv[])
{
	if(argc<3)
		return 0;
	pthread_t thrd1,thrd2;
	char *writefile=argv[1];
	char *readfile=argv[2];
	pthread_create(&thrd1,NULL,writefofi,(void *)writefile);
	pthread_create(&thrd2,NULL,readfofi,(void *)readfile);
	pthread_join(thrd1,NULL);
	pthread_join(thrd2,NULL);
	return 0;
}

/*
 * test2.c
 *
 *  Created on: 2016年7月26日
 *      Author: Andy_Cong
 */


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include<errno.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void *writefofi(void *arg)
{
	char *filename=(char *)arg;
	int fd=open(filename,O_WRONLY);
	if(fd==-1)
	{
		printf("open error is: %s\n",strerror(errno));
		return NULL;
	}
	char buf[1024];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		read(STDOUT_FILENO,buf,sizeof(buf));
		write(fd,buf,strlen(buf));
	}
	close(fd);
	return NULL;
}
void *readfofi(void *arg)
{
	char *filename = (char *) arg;
	int fd = open(filename, O_RDONLY);
	if (fd == -1)
	{
		printf("open error is: %s\n", strerror(errno));
		return NULL;
	}
	char buf[1024];
	while (1)
	{
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("%s",buf);
	}
	close(fd);
	return NULL;
}


int main(int argc,char *argv[])
{
	if(argc<3)
		return 0;
	pthread_t thrd1,thrd2;
	char *writefile=argv[1];
	char *readfile=argv[2];
	pthread_create(&thrd1,NULL,writefofi,(void *)writefile);
	pthread_create(&thrd2,NULL,readfofi,(void *)readfile);
	pthread_join(thrd1,NULL);
	pthread_join(thrd2,NULL);
	return 0;
}





运行结果:



Logo

更多推荐