🌟hello,各位读者大大们你们好呀🌟
🍭🍭系列专栏:【Linux初阶】
✒️✒️本篇内容:shell重定向功能的代码实现
🚢🚢作者简介:计算机海洋的新进船长一枚,请多多指教( •̀֊•́ ) ̖́-
文章目录
前言
本篇博客主要讲述 shell重定向功能的代码实现,其他简易shell的基础功能实现可查看作者这篇文章 -> 【Linux初阶】进程替换的应用 - 简易命令行解释器的实现
有对重定向基础概念和实现不清楚的同学可以看这篇文章 -> 【Linux初阶】基础IO - 文件管理(深入理解文件描述符) | 重定向
一、Makefile文件
myshell:myshell.c
gcc - o $@ $ ^ -std = c99 # - DDEBUG
.PHONY:clean
clean :
rm - f myshell
二、shell代码修改(添加重定向功能)
1.指令切割
实现重定向前,先要对指令做分割
- “ls -a -l -i > myfile.txt” -> “ls -a -l -i” “myfile.txt” ->
- “ls -a -l -i >> myfile.txt” -> “ls -a -l -i” “myfile.txt” ->
- “cat < myfile.txt” -> “cat” “myfile.txt” ->
该段代码需要添加在,指令获取且去除 \n 之后
#define NONE_REDIR 0 //宏定义类型
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3
#define trimSpace(start) do{
\ //trimSpace过滤函数的实现
while(isspace(*start)) ++start;\ //isspace判断*start是不是空格,是就++跳过
}while(0) //isspace - #include <ctype.h>
int redirType = NONE_REDIR; // 定义初始类型
char* redirFile = NULL;
// "ls -a -l -i > myfile.txt" -> "ls -a -l -i" "myfile.txt" ->
void commandCheck(char* commands)
{
assert(commands);
char* start = commands; //定义指令检索始末位
char* end = commands + strlen(commands);
while (start < end) //合法范围内循环遍历
{
if (*start == '>')
{
*start = '\0';
start++;
if (*start == '>')
{
// "ls -a >> file.log"
redirType = APPEND_REDIR;
start++;
}
else
{
// "ls -a > file.log"
redirType = OUTPUT_REDIR;
}
trimSpace(start); //trimSpace过滤函数
redirFile = start;
break;
}
else if (*start == '<')
{
//"cat < file.txt"
*start = '\0'; //对指令进行拆分
start++;
trimSpace(start); //trimSpace过滤函数(实现在上面),对 *start指向的空格进行过滤
// 填写重定向信息
redirType = INPUT_REDIR;
redirFile = start;
break;
}
else
{
start++;
}
}
}
// "ls -a -l -i > myfile.txt" -> "ls -a -l -i" "myfile.txt" ->
// "ls -a -l -i >> myfile.txt" -> "ls -a -l -i" "myfile.txt" ->
// "cat < myfile.txt" -> "cat" "myfile.txt" ->
commandCheck(lineCommand);
———— 我是一条知识分割线 ————
2.需要子进程实现重定向
原来的子进程执行代码
if (id == 0)