2
我正在實現的是(更簡單)版本的bash。其中一個任務是接受命令:將分叉的進程輸出重定向到父進程C
$ bg <command> <arguments>
這一操作將一個新的進程,然後使用<command>
和<arguments>
作爲參數運行的新進程execvp()
。問題是,當我從子進程捕獲輸出時,我使用pipe()
,並且在從子進程獲取輸出並在需要時輸出它之後,我似乎無法切換回STDIN
作爲我的父級(shell)過程,這會在下次需要接受輸入時導致段錯誤。
這是我的「bg」功能的一部分。
ChildPID = fork();
if (ChildPID < 0) {
/* There is an error */
printf("Error forking the process.\n");
exit(1);
}
if (ChildPID >= 0) {
if (ChildPID == 0) { /* Child Process */
close(m_pipefd[0]);
dup2(m_pipefd[1], STDOUT_FILENO);
close(m_pipefd[1]);
//sleep(5);
err = execvp(optionsPTR[0], optionsPTR);
switch (errno) {
case ENOENT:
printf("RSI: %s: command not found\n", optionsPTR[0]);
break;
case EACCES:
printf("RSI: %s: Permission denied\n", optionsPTR[0]);
break;
}
exit(1);
}
else { /* Parent Process */
WaitErr = waitpid(ChildPID, &status, WNOHANG | WUNTRACED);
return(0); /* to main */
}
}
return 0;
以及代碼,當我從過程完成後從管道輸出。
close(m_pipefd[1]);
dup2(m_pipefd[0], STDIN_FILENO);
while(fgets(buffer, sizeof(buffer), stdin)) {
buf = buffer;
printf("%s\n", buf);
}
close(m_pipefd[0]);
所以文藝青年最愛的版本是,我需要捕捉孩子後重置回標準輸入父進程處理的輸出。
感謝,
布拉登
謝謝,我不知道我在想什麼。這解決了它。 – Braden 2010-10-01 01:52:00