2012-01-09 26 views
1

我嘗試了fork()一個會運行ls命令的子。C中的execlp()在執行後沒有給出提示回覆

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <stdlib.h> 

int main() { 

    if (fork()==0){ //child 
     execlp("ls", "ls", "-l", (char*)0); 
     exit(1); 
    } 

    fflush(stderr); //doesn't fix my problem 
    fflush(stdout); //doesn't fix my problem 
    exit(0); 
} 

這可以正常工作,但遊標卡在執行子代後會卡住。我必須按回車鍵才能取回終端。這是爲什麼?

回答

2

您的主進程在子進程完成之前退出。等待子進程使用wait()或waitpid()退出。

+0

謝謝。解決了它:) – Pithikos 2012-01-09 15:14:59

+0

如果父母和孩子退出,我怎樣才能得到孩子的地位?我需要使用waitpid嗎?何時何地可以使用它? – kapilddit 2014-03-27 10:35:31