[英]Redirecting child process without redirecting parent process
我正在嘗試重定向子進程的輸入和 output stream,沒有重定向父進程輸入和 Z78E6221F6393D1356681DB398F14CE6D28223B44CFZAFD5E7BZ。 我的想法是檢查命令行中是否有輸入\輸出,如果有則重定向到它,然后在必要時分叉並等待子進程完成它的過程,並最終重定向回stdin
和stdout
。 問題是這段代碼不會以某種方式重定向回stdin
和stdout
,並且父進程保留在以前的流中。 這是我的代碼:
typedef struct cmdLine
{
char * const arguments[MAX_ARGUMENTS]; /* command line arguments (arg 0 is the command)*/
int argCount; /* number of arguments */
char const *inputRedirect; /* input redirection path. NULL if no input redirection */
char const *outputRedirect; /* output redirection path. NULL if no output redirection */
char blocking; /* boolean indicating blocking/non-blocking */
int idx; /* index of current command in the chain of cmdLines (0 for the first) */
struct cmdLine *next; /* next cmdLine in chain */
} cmdLine;
void execute(cmdLine *pCmdLine){
FILE * input = NULL;
FILE * output = NULL;
if(pCmdLine->inputRedirect != NULL){
close(fileno(stdin));
input = fopen(pCmdLine->inputRedirect, "r+"); //open for child
}
if(pCmdLine->outputRedirect != NULL){
close(fileno(stdout));
output = fopen(pCmdLine->outputRedirect, "ab+"); //open for child
}
pid = fork();
if(pCmdLine->blocking == 1) {
waitpid(pid, NULL, 0); //wait for chile to finish
if (input){ //redirect to stdin
close(input);
fopen(stdin, "r+");
fflush(stdin);
}
if (output){ //redirect to stdout
close(output);
fopen(stdout, "ab+");
fflush(stdout);
}
}
if(pid == 0){
execvp(pCmdLine-> arguments[0],pCmdLine->arguments); //exec child
perror("execution went wrong!");
exit(-1);
}
}
我該怎么做才能正確而優雅?
注意:不使用 dup2 和 pipe 或任何其他庫而不是那些:unistd.h、stdio.h、stdlib.h、string.h、sys/wait.h
重定向應分別通過關閉和重新打開標准輸入和標准 output 來完成。 並且只能在子進程中完成。
這可以通過在子分支中完成
pid_t pid = fork();
if (pid == -1) {
// error handling
perror("fork");
} else if (pid == 0) {
// Now we're in the child process
if (pCmdLine->inputRedirect != NULL) {
fclose(stdin);
input = fopen(pCmdLine->inputRedirect, "r+"); // open for child
}
if (pCmdLine->outputRedirect != NULL) {
fclose(stdout);
output = fopen(pCmdLine->outputRedirect, "ab+"); // open for child
}
execvp(pCmdLine->arguments[0], pCmdLine->arguments); // exec child
perror("execution went wrong!");
exit(-1);
} else {
// Now we're in the parent process
waitpid(pid, NULL, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.