[英]how to redirect output from cd in a shell written in C
我正在用C寫一個基本的shell,我實現了所有重定向操作符,但是,當我嘗試重定向“ cd”時,我遇到了這個問題:
cd無需任何輸出重定向即可完美運行,但是
當我嘗試做這樣的事情時:
cd inexistant_directory > output_file
在bash中,未創建輸出文件,運行該命令的確會重定向標准輸出,如我之前所述,使用外部命令的重定向運算符可以正常工作
當我遇到cd命令時,我打電話
char*path = get_path(parameters); //implemented by me, works on rest of the cases
int ret =chdir(path);
我不是在子進程中而是在父進程(shell進程本身)中稱呼它
我究竟做錯了什么 ?
謝謝,
PS:運行此操作系統的操作系統是Ubuntu 12.10,但是代碼符合POSIX
LE:我無法發布整個代碼,因為它大約需要600行,
這是我的邏輯
if(internal_command) {
//do quit, exit or cd
} else if (variable_assignemt){
//do stuff
} else {
// external command
pid = fork();
if(pid == -1) {
//crash
} else if (pid == 0) {
do_redirects()
call_external_cmd
}
default :
wait(pid, &status);
因此,我認為要解決此問題,我需要在parrent(shell進程)中重定向stdout並在執行命令后將其還原
在父進程(shell)中不重定向stdout確實是cd有害行為的原因,我的解決方案是:
if(we_have_out_redirection == 1) {
if(out != NULL) {
char *outParrent = out;
fflush(stdout);
outBackup = dup(STDOUT_FILENO); //I save stdout for future restoration
int fd = open(outParrent, O_WRONLY | O_CREAT | O_TRUNC, 0644); //open output file
int rc;
rc = dup2(fd, STDOUT_FILENO); //redirect stdout
retval = chdir(out); //execute cd command
//restore stdout
close(fd);
fflush(stdout);
rc = dup2(outBackup, 1);
close(outBackup);
}
}
感謝Jake223指出我忘了重定向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.