2013-03-07 54 views
0

我正在写一个简单的程序,以更好地理解fork(),wait()和execvp()。我的问题是,我运行该程序后,控制不会传回到shell,我不知道为什么。我想要的是能够在代码完成后向shell输入另一个命令。我看了一下this,但我认为这不适用于我的情况。我基本上只是从here找到的复制代码。fork()后失去控制

输入/输出(#是在我输入行的前面,尽管不是输入的一部分):

shell> # gcc test.c -o test 
shell> # ./test 
input program (ls) 
# ls 
input arg (.) 
# . 
test test.c extra.txt 
# a;dlghasdf 
# go back 
# :(

我的代码:

int main(void) { 
    //just taking and cleaning input 
    printf("input program (ls)\n"); 
    char inputprogram [5] = {0,0,0,0,0}; 
    fgets(inputprogram,5,stdin); //read in user command 
    int i; 
    for(i = 0; i < 5; i++) { 
     if(inputprogram [i] == '\n'){ 
      inputprogram[i] = 0; 
     } 
    } 

    printf("input arg (.)\n"); 
    char inputarg [5] = {0,0,0,0,0}; 
    fgets(inputarg,5,stdin); //read in user command 
    for(i = 0; i < 5; i++) { 
     if(inputarg [i] == '\n'){ 
      inputarg[i] = 0; 
     } 
    } 

    char per []= {inputarg[0], 0}; 
    char *arg [] = {inputprogram, per , NULL}; 

    int status = 0; 
    pid_t child; 

    //the fork(), execvp(), wait() 
    ////////////////////////////////// 
    if ((child = fork()) < 0) { 
     /* fork a child process   */ 
     printf("*** ERROR: forking child process failed\n"); 
     exit(1); 
    } else if(child == 0){ 
     execvp(inputprogram, arg); 
     exit(1); 
    } else { 
     while(wait(&status != child)); 
    } 

    return EXIT_SUCCESS; 
} 

回答

2

此行

while(wait(&status != child)); 

不正确

您需要

wait(&status); 

或者使用waitpid - 见here

+0

不错的,它的工作。为什么我不需要循环?是因为我只有一个孩子的过程?我在看这个[http://stackoverflow.com/questions/2708477/fork-and-wait-with-two-child-processes]这就是为什么我很困惑 – Daniel 2013-03-07 03:25:57

+0

就像是一个父母它是一件容易得多一个孩子要照顾。如果你有两个,你需要一个循环(眼睛在你的脑后)。 – 2013-03-07 03:29:50