2017-02-15 68 views
1

我有一个程序似乎挂在父进程中。这是一个模拟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. 

这是我第一次分裂过程和叉子工作()。我在这里错过了什么吗?当我同时运行它时应该选择流程还是类似的东西?欢迎任何帮助,谢谢!

+0

,如果你添加一个'\ N'提示行预期,它的工作原理? –

回答

3

你的代码实际上工作正常。唯一的问题是,你吐出“太快”的提示,新的提示出现在命令输出之前。在此处查看测试输出:

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 & 

哈努哈利

+0

这个顺便说一句,在你的shell提示符下发出ls -al&命令。当新的shell提示符出现在中间的某个位置时,它通常在任何命令输出之前都会出现“空”行。 – Hannu

+1

谢谢,我明白你的意思了! osh>出现较早,并不是因为它不起作用,而是因为它确实有效。我对它应该如何工作的期望只是关闭。非常感谢! –