【发布时间】:2018-08-17 10:57:29
【问题描述】:
目标:要设计一个 linux shell,它会提示用户接受输入,创建一个新进程来执行该命令,然后终止/退出该进程。这是我的代码
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
using namespace std;
string cmd; //global string so cmd copied to child to execute
void HandleAsParent(){
cout<<"Linux Shell 1.0\n";
string s;
while (!exitflag) {
cout<<"myShell>";
getline(cin,cmd); //Take user input
fork();
wait(NULL);
}
}
void HandleAsChild(){
cout<<"Executing";
system(cmd.c_str());
}
int main() {
pid_t p = fork();
if(p != 0){
HandleAsParent(); //This is parent process
}
else {
HandleAsChild(); //This is child process
}
}
问题在于,由于 main 中的第一个 fork() 调用,
myShell>正在执行
在程序运行时显示在第一行,而不仅仅是
我的壳>
。 我能够理解为什么会发生这种情况,但无法弄清楚如何阻止第一个子进程被执行。 请建议我解决问题的方法/解决方案。
编辑 1:这是我的作业之一(用于学习 UNIX 进程) 问题,并明确说明程序“提示 用户获取命令,解析命令,然后使用 子进程"
【问题讨论】:
-
显示的代码中没有任何内容实际上需要
fork()ing。你到底希望fork()ing 完成什么,然后在没有父进程等待的情况下在子进程中执行命令?只需摆脱无用的叉子。问题解决了。 -
这仍然是WIP,我卡在这里没有进一步编码,当然,父母会等待孩子完成然后再继续(显示提示)
-
@SamVarshavchik 我已编辑添加一个 wait() 语句。
-
只需从 main 中移除 fork。它应该只包含
int main() { HandleAsParent(); return 0; } -
是的,这是我的作业(用于学习 UNIX 进程)问题之一,并且明确指出程序“提示用户输入命令,解析命令,然后执行它一个子进程“@Scheff