我正在用 c 制作我自己的 shell,我現在正在嘗試制作一個將 shell 的標準錯誤重定向到特定檔案的函式,一個設法顯示標準錯誤當前去向的選項,另一個能夠重置標準錯誤到它原來的樣子。
我已經實作了這個代碼來重定向標準錯誤:
int fd, new_fd;
if((fd = open(tokens[1], O_RDWR)) == -1){
perror("Error opening: ");
return 0;
}
if(dup2(fd, STDERR_FILENO) == -1){
perror("Error: ");
}
if(close(fd) == -1){
perror("Error closing: ");
}
現在,我找不到任何可以恢復或顯示 stderr 現在要去哪里的選項,如果有人能幫助我實作這一點,那就太棒了!
if(tokens[1] == NULL){
//Shows where the standard error is currently going to
return 0;
}
if(strcmp(tokens[1], "-reset") == 0){
//Restores the standard error to what it was originally
return 0;
}
uj5u.com熱心網友回復:
要恢復stderr,請dup在替換之前使用將原始檔案保存到新的檔案描述符中。如果您愿意,您可以稍后從該備份中恢復它。如果你不這樣做,只是用你打開的檔案替換它,它會在dup2關閉它替換的描述符時丟失,這樣舊的唯一描述符就會stderr丟失。
int backup = dup(STDERR_FILENO);
// ... later
dup2(backup, STDERR_FILENO);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369695.html
