#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <fcntl.h>
using namespace std;
int main()
{
int pd[2];
int fd;
pid_t pid;
int n;
char * r_buf[1024]={0};
mkfifo("/root/Desktop/namepipe",O_CREAT|O_EXCL);
if((pid = fork())<0)
{
cout<<"fork error"<<endl;
exit(1);
}
if(pid == 0)
{
fd=open("/root/Desktop/namepipe.txt",O_RDWR|O_NONBLOCK);
close(0);
dup(fd);
cout<<"child process cout:"<<endl;
while(n=read(fd,r_buf,1024) > 0)
{
printf("%s ",r_buf);
}
close(fd);
}
else if(pid > 0)
{
int filedes;
if((filedes=open("/root/Desktop/namepipe.txt",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))<0)
fprintf(stderr,"%s ","open file error");
close(1);
dup(filedes);
close(filedes);
使用C语言将ls命令重定向实现
最新推荐文章于 2022-12-22 06:00:00 发布
本文介绍了如何使用C语言将ls命令的输出重定向到文件中,通过关闭标准输出、使用dup函数和execlp函数执行ls命令,实现了不将信息打印到终端而是输出到指定文本文件。结合fork()进程,可以进一步实现管道机制。
摘要由CSDN通过智能技术生成