关于管道基础理论知识:
https://blog.youkuaiyun.com/qq_42418668/article/details/95184701
有名管道的使用编程举例(A进程获取用户的输入写入管道,B进程获取管道的内容并打印到标准输出上面)
A.c:
/*================================================================
* Copyright (C) 2019 . All rights reserved.
*
* 文件名称:A.c
* 创 建 者:gaojie
* 创建日期:2019年07月06日
* 描 述:
*
================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd;
fd = mkfifo("wordfifo",0644);
if(fd == -1)
{
printf("管道创建失败\n");
exit(0);
}
fd = open("wordfifo",O_WRONLY);
char buf[128]={0};
printf("请输入相关字符\n");
fgets(buf,127,stdin);
buf[strlen(buf) - 1]=0;
printf("%s\n",buf);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
B.c:
/*================================================================
* Copyright (C) 2019 Sangfor Ltd. All rights reserved.
*
* 文件名称:B.c
* 创 建 者:gaojie
* 创建日期:2019年07月06日
* 描 述:
*
================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd;
fd = open("wordfifo",O_RDONLY);
if(fd == -1)
{
printf("打开管道失败\n");
exit(0);
}
char buf[128]={0};
read(fd,buf,128);
buf[strlen(buf) - 1]=0;
close(fd);
remove("wordfifo");
printf("%s\n",buf);
fd = open("a.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fd == -1)
{
printf("打开a.txt失败\n");
exit(0);
}
buf[strlen(buf)]=0;
char *p = buf;
while(*p != 0)
{
*p = tolower(*p);
p++;
}
int n = write(fd,buf,strlen(buf));
if(n==-1)
{
printf("写入文件失败\n");
close(fdd);
exit(0);
}
printf("成功\n");
close(fd);
exit(0);
}
运行结果:
先运行A,A阻塞等待其他进程打开管道文件的读端:
再启动B,A的open函数返回继续执行程序。
在A端输入数据
在B端查看结果:
无名管道的使用(父进程给子进程通过管道传递数据,子进程拿到数据之后将其中的大写字母转化为小写字母再将其写入a.txt文件中)
/*================================================================
* Copyright (C) 2019 All rights reserved.
*
* 文件名称:A.c
* 创 建 者:gaojie
* 创建日期:2019年07月06日
* 描 述:
*
================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd[2];
pipe(fd);
if(fork() == 0)
{
//关闭写端
close(fd[1]);
char buf[128]={0};
read(fd[0],buf,128);
close(fd[0]);
buf[strlen(buf)]=0;
int fdd = open("a.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fdd == -1)
{
printf("创建文件失败\n");
exit(0);
}
char *p= buf;
while(*p!=0)
{
*p = tolower(*p);
p++;
}
write(fdd,buf,strlen(buf));
close(fd);
exit(0);
}
else
{
close(fd[0]);
char buf[128]={0};
fgets(buf,128,stdin);
buf[strlen(buf)]=0;
write(fd[1],buf,strlen(buf));
close(fd[1]);
wait(NULL);
exit(0);
}
}