我有一个程序似乎卡在父进程中。这是一个模拟 bash 程序,它接受像 bash 这样的命令,然后运行它们。代码如下。 (请注意,这是没有错误检查的简化代码,因此它更易于阅读。假设它全部正确嵌套在 main 函数中)
#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;
}
}
这里的问题与我使用“&”并激活同时运行标志有关。这使得 parent 不再需要等待,但是当我这样做时,我失去了一些功能。
预期输出:
osh> ls-a &
//Outputs a list of all in current directory
osh>
所以我希望它同时运行它们,但将终端的控制权交还给我。但是我得到了这个。
实际结果:
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.
这是我第一次使用拆分进程和 fork()。我在这里错过了什么吗?当我同时运行它时,我应该选择进程还是类似的东西?欢迎任何帮助,谢谢!
最佳答案
您的代码实际上工作正常。唯一的问题是,你“太快”吐出了提示,新的提示出现在命令输出之前。在此处查看测试输出:
osh> ls -al &
osh> total 1944 --- LOOK HERE
drwxrwxrwt 15 root root 4096 Feb 15 14:34 .
drwxr-xr-x 24 root root 4096 Feb 3 02:13 ..
drwx------ 2 test test 4096 Feb 15 09:30 .com.google.Chrome.5raKDW
drwx------ 2 test test 4096 Feb 15 13:35 .com.google.Chrome.ueibHT
drwx------ 2 test test 4096 Feb 14 12:15 .com.google.Chrome.ypZmNA
请参阅“查看此处”行。新提示在那里,但 ls 命令输出稍后出现。您的应用程序响应新命令,即使在命令输出之前显示提示也是如此。您可以使用不产生任何输出的命令来验证所有这些,例如
osh> sleep 10 &
汉奴
关于c - 进程在 C 中的父进程中挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251937/