1. 有名管道特点:

        1.有名管道是对无名管道的改进,它可以使互不相关的两个进程互相通信,并且在文件系统中可见,可以通过文件名来找到。

        2.半双工的通信方式,进程通过文件IO来操作有名管道。

        3.有名管道遵循先进先出原则,不支持lseek()。

  1.       2.有名管道的创建

                  配合IO即可实现两个进程间的全双工通信。

                3.代码

                1.父进程发,子进程收,(父进程间收发,子进程间收发)

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
	unlink("myfifo1");
	unlink("myfifo2");
	if(mkfifo("myfifo1",0777)<0)
	{
		perror("fifo1 create error");
		return -1;
	}
	else
	{
		printf("mkfifo1 OK!\n");
	}
	if(mkfifo("myfifo2",O_CREAT|0777)<0)
	{
		perror("fifo2 create error");
		return -1;
	}
	else
	{
		printf("mkfifo2 OK!\n");
	}
	char buf[20]={'\0'};
	pid_t pid;
	pid=fork();
	if(pid<0)
	{
		perror("fork error");
		return -1;
	}
	else if(0==pid)
	{
		int fw2=open("myfifo2",O_RDONLY);
		if(fw2<0)
		{
			perror("open myfifo2 error");
			return -1;
		}
		while(1)
		{
			memset(buf,0,sizeof(buf));
			read(fw2,buf,sizeof(buf));
			printf("%s",buf);
			if(strncmp(buf,"exit",4)==0)
			{
				break;
			}
		}
		close(fw2);
		exit(0);
	}
	else if(pid>0)
	{
		int fw1=0;
		fw1=open("myfifo1",O_WRONLY);
		if(fw1<0)
		{
			perror("open myfifo1 error");
			return -1;
		}
		while(1)
		{
            waitpid(-1,NULL,WNOHANG);
			fgets(buf,sizeof(buf),stdin);
			write(fw1,buf,sizeof(buf));
			if(strncmp(buf,"exit",4)==0)
			{
				break;
			}
		}
		close(fw1);
	}
	return 0;
}

                2.父进程收,子进程发

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
	char buf[20]={'\0'};
	pid_t pid;
	pid=fork();
	if(pid<0)
	{
		perror("fork error");
		return -1;
	}
	else if(0==pid)
	{
		int fw2=open("myfifo2",O_WRONLY);
		if(fw2<0)
		{
			perror("open myfifo2 error");
			return -1;
		}
		while(1)
		{
			fgets(buf,sizeof(buf),stdin);
			write(fw2,buf,sizeof(buf));
			if(strncmp(buf,"exit",4)==0)
			{
				break;
			}
		}
		close(fw2);
		exit(0);
	}
	else if(pid>0)
	{
		int fw1=0;
		fw1=open("myfifo1",O_RDONLY);
		if(fw1<0)
		{
			perror("open myfifo1 error");
			return -1;
		}
		while(1)
		{
			waitpid(-1,NULL,WNOHANG);
			memset(buf,0,sizeof(buf));
			read(fw1,buf,sizeof(buf));
			printf("%s",buf);
			if(strncmp(buf,"exit",4)==0)
			{
				break;
			}
		}
		close(fw1);
	}
	return 0;
}

效果如下:

 退出时要先退出子进程,再退父进程,否则子进程就无法退出,变为孤儿进程,继续运行,需要利用信号将其杀死。

Logo

更多推荐