我正在撰寫自己的自定義 shell,作為專案的一部分,當程式從用戶輸入中讀取“<”或“>”字符時,它需要將 stdin 和 stdout 重定向到自定義檔案。我在下面為此撰寫了一個函式。我苦苦掙扎的部分是,即使我以幾乎相同的方式撰寫輸入和輸出重定向的代碼,輸出重定向似乎按預期作業,而輸入重定向卻沒有。請看下面的代碼:
void inOutReDirector(char **toks, char *inputFile, char *outputFile, int *fd0, int *fd1, int *in, int *out) {
fflush(0);
for (int i = 0; toks[i] != NULL; i ) {
if (strcmp(toks[i], "<") == 0) {
toks[i] = NULL;
strcpy(inputFile, toks[i 1]);
toks[i 1] = NULL;
*in = 1;
}
if (strcmp(toks[i], ">") == 0) {
toks[i] = NULL;
strcpy(outputFile, toks[i 1]);
toks[i 1] = NULL;
*out = 1;
}
}
//input redirection
if (*in == 1) {
if ((*fd0 = open(inputFile, O_RDONLY, 0)) < 0) {
printf("Couldn't open input file: %s", strerror(errno));
exit(1);
}
dup2(*fd0, STDIN_FILENO);
close(*fd0);
}
//output redirection
if (*out == 1) {
if ((*fd1 = creat(outputFile, 0644)) < 0) {
printf("Couldn't open output file: %s", strerror(errno));
exit(1);
}
dup2(*fd1, STDOUT_FILENO);
close(*fd1);
}
}
下面是我如何從我的 main 呼叫這個函式:
int main() {
char *toks[STD_INPUT_SIZE] = {0};
int fd0, fd1, in = 0, out = 0;
char inputFile[64], outputFile[64];
pid_t pid;
while (1) {
//print prompt
//get user input
pid = fork();
if (pid < 0) {
printf("%s \n", strerror(errno));
exit(1);
}
int stopNeeded = strcmp(toks[0], "exit") == 0;
if (pid == 0 && !stopNeeded) {
pathFinder(toks, shellInput, currentDir); //finding path for execv input
inOutReDirector(toks, inputFile, outputFile, &fd0, &fd1, &in, &out); // I/O redirection
if (execv(shellInput, toks) != 0) {
char *errMsg = strerror(errno);
printf("%s \n", errMsg);
//clean the old contents of toks
for (int i = 0; i < STD_INPUT_SIZE; i) {
free(toks[i]);
toks[i] = NULL;
}
exit(1);
}
}
if (pid > 0) {
pid_t childPid = waitpid(pid, NULL, 0);
(void) childPid;
}
}
return 0;
}
這是我的終端螢屏的輸出重定向示例
$ ls > output.txt
$
這將創建“output.txt”檔案并在當前目錄的該檔案中列印結果。
這是從我的終端螢屏進行輸入重定向的示例
$ cat < output.txt
$
輸入重定向無法正常作業。它列印提示并等待輸入,而不是在我的終端中顯示 output.txt 的內容。
感謝您提前提供的任何幫助!
uj5u.com熱心網友回復:
問題應該出在函式的這一行inOutReDirector
if (strcmp(toks[i], ">") == 0) {
應該改為
else if (strcmp(toks[i], ">") == 0) {
當toks[i]等于“<”時,toks[i]上面會設定為NULL,這行呼叫strcmp會導致SIGSEGV,所以子行程退出,后續execv不會執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/465352.html
上一篇:如何將檔案中每一行的第一個單詞放入變數中,將其卷曲并將輸出附加到新檔案中
下一篇:如何獲取ADBshell流量?
