我有一个程序似乎挂在父进程中。这是一个模拟bash程序,接受像bash这样的命令,然后运行它们。代码如下。 (请注意,这是简化的代码没有错误检查,因此会更易于阅读。假设所有正确的嵌套主函数中)在这里进程挂起在父进程中C
#define MAX_LINE 80
char *args[MAX_LINE/2 + 1];
while(should_run){
char *inputLine = malloc(MAX_LINE);
runConcurrently = 0; /*Resets the run in background to be line specific */
fprintf(stdout, "osh> "); /*Command prompt austhetic */
fflush(stdout);
/*User Input */
fgets(inputLine, MAX_LINE, stdin);
/*Reads into Args array */
char *token = strtok(inputLine, " \n");
int spot = 0;
while (token){
args[spot] = token;
token = strtok(NULL, " \n");
spot++;
}
args[spot] = NULL;
/* checks for & and changes flag */
if (strcmp(args[spot-1], "&") == 0){
runConcurrently = 1;
args[spot-1] = NULL;
}
/* Child-Parent Fork Process */
pid_t pid;
pid = fork(); /*Creates the fork */
if (pid == 0){
int run = execvp(args[0], args);
if (run < 0){
fprintf(stdout, "Commands Failed, check syntax!\n");
exit(1);
}
}
else if (pid > 0) {
if (!runConcurrently){
wait(NULL);
}
}
else {
fprintf(stderr, "Fork Failed \n");
return 1;
}
}
的问题有,当我使用“&”并激活做同时运行标志。这使得父母不再需要等待,但是当我这样做时,我失去了一些功能。
预期输出:
osh> ls-a &
//Outputs a list of all in current directory
osh>
所以我希望它concurently运行它们,但我给终端的控制了。但是,我得到了这个。
实际结果:
osh> ls -a &
//Outputs a list of all in current directory
<---- Starts a new line without the osh>. And stays like this indefinitely
如果我输入一些东西到这个空白区的结果是:
osh> ls -a &
//Outputs a list of all in current directory
ls -a
//Outputs a list of all in current directory
osh> osh> //I get two osh>'s this time.
这是我第一次分裂过程和叉子工作()。我在这里错过了什么吗?当我同时运行它时应该选择流程还是类似的东西?欢迎任何帮助,谢谢!
,如果你添加一个'\ N'提示行预期,它的工作原理? –