阅读背景:

使用C语言将ls命令重定向实现

来源:互联网 
#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);
		execlp("ls","ls","-l",(char * )0);
		return 0;
	}
	return 0;
}
#include <unistd.h>
#include <stdlib.h>
#includ



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: