2011-10-03 44 views
0

嘿傢伙我想用C++編寫一個shell,我遇到了與exec命令一起使用輸入文件的功能問題。例如,Linux中的bc shell能夠執行「bc < text.txt」,它以批處理方式計算文本中的行。我正在嘗試用我的外殼來做同樣的事情。東西沿線︰exec家族與文件輸入

char* input = 「input.txt」; 
execlp(input, bc, …..) // I don’t really know how to call the execlp command and all the doc and search have been kind of cryptic for someone just starting out. 

這甚至有可能與exec命令?或者我將不得不逐行閱讀並在for循環中運行exec命令?

+1

execlp用於啓動單個進程。您將不得不逐行讀取輸入文件並分別處理每個命令。 – CurtisB

+0

execlp()只有在編譯時知道命令和參數時才真正用到,而這在shell中很少使用。你應該假設你將要使用exec *()系列函數的execv *()部分。 –

回答

1

重定向由shell執行 - 它不是bc的參數。您可以調用的bash(的bash -c "bc < text.txt"等效)

例如,你可以使用execvp"bash"和參數列表

"bash" 
"-c" 
"bc < text.txt" 
+0

如果他正在編寫一個shell,他不應該使用任何其他shell來處理這個問題。 –

+0

@BenVoigt這是真的,但聲明「Linux中的bc shell能夠做到」bc

3

您可以打開的文件的文件參數,然後dup2()文件描述符標準輸入,或者可以關閉標準輸入,然後打開文件(這是因爲標準輸入是描述符0,open()返回編號最小的可用描述符)。

const char *input = "input.txt"; 
int fd = open(input, O_RDONLY); 
if (fd < 0) 
    throw "could not open file"; 
if (dup2(fd, 0) != 0) // Testing that the file descriptor is 0 
    throw "could not dup2"; 
close(fd);    // You don't want two copies of the file descriptor 
execvp(command[0], &command[0]); 
fprintf(stderr, "failed to execvp %s\n", command[0]); 
exit(1); 

你可能會想比throw聰明的錯誤處理,這不僅是因爲這是孩子的過程,它是需要知道父母。但throw網站標記處理錯誤的點。

注意close()