minishell中實作重定向功能
- 捕捉鍵盤輸入 --ls -a \0> test.txt
- 決議輸入資訊(重定向型別、重定向檔案名稱、命名名稱、運行引數)
· 根據命令中的>確定是否包含重定向,根據個數確定重定向型別
· >之前是基礎指令部分,決議出命令名稱和運行引數
· >之后是重定向資訊部分,決議出重定向型別、重定向檔案名稱 - 創建子行程
- 在程式替換之前,進行標準輸出重定向到指定的檔案,open,dup2
- 在子行程中進行程式替換(替換失敗要退出子行程)
- 在父行程中進行行程等待
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main (int argc, char *argv[])
{
while(1) {
printf("[user@host path]$ ");
fflush(stdout);
char cmd[1024] = {0};
fgets(cmd, 1023, stdin);
cmd[strlen(cmd) - 1] = '\0';
int direct_flag = 0;//0-沒有,1-清空,2-追加
char *ptr = cmd;
char *redirect_file = NULL;
//[ ls -a \0\0 text.txt\0]
while(*ptr != '\0') {
if (*ptr == '>') {
direct_flag = 1;
*ptr = '\0';
ptr++;
if (*ptr == '>') {
direct_flag = 2;
*ptr = '\0';
ptr++;
}
while(*ptr != '\0'&&*ptr == ' ')ptr++;
redirect_file = ptr;
while(*ptr != '\0'&&*ptr != ' ')ptr++;
*ptr = '\0';
}
ptr++;
}
ptr = cmd;
char *arg[32] = {NULL};
int ac = 0;
//[ ls -a ]
while(*ptr != '\0') {
if (!isspace(*ptr)) {
arg[ac] = ptr;
ac++;
while(*ptr != '\0' && !isspace(*ptr)) ptr++;
*ptr = '\0';
}
ptr++;
}
arg[ac] = NULL;
if (strcmp(arg[0], "cd") == 0) {
chdir(arg[1]);
continue;
}
pid_t pid = fork();
if (pid < 0) {
continue;
}else if (pid == 0) {
if (direct_flag == 1) {
int fd;
fd = open(redirect_file,
O_CREAT|O_RDWR|O_TRUNC, 0664);
dup2(fd, 1);
}else if (direct_flag == 2) {
int fd;
fd = open(redirect_file,
O_CREAT|O_RDWR|O_APPEND, 0664);
dup2(fd, 1);
}
execvp(arg[0], arg);
exit(-1);
}
wait(NULL);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/274836.html
標籤:其他
