2015-02-12 126 views
1

我有以下兩個簡單的程序:EXECL沒有運行程序

bye.cc

#include <iostream> 

int main() 
{ std::cout << "Bye bye bye world" << std::endl; } 

hello.cc

#include <cstdlib> 
#include <unistd.h> 
#include <sys/wait.h> 
#include <iostream> 
using namespace std; 


int main() 
{ 
    int status; 

    cout << "Hello world" << endl; 

    int pid = fork(); 
    if (pid != 0) { 
     cout << "I am parent - " << pid << endl; 
     // wait for child to finish up...... 
     cout << "Waiting for child to finish" << endl; 
     wait(&status); 
     cout << "Child finished, status " << status << endl; 
    } else { 
     cout << "--- I am child - " << pid << endl; // **Note** 
     execl("bye", ""); 
     cout << "--- I am sleeping" << endl; 
     sleep(3); 
     exit(11); 
    } 
} 

在hello.cc,如果標記爲「Note」的行被啓用(未被評論),我得到預期行爲,睡眠(3)未被執行,並且「bye」被執行,期望msg打印到控制檯。

$ ./hello 
Hello world 
I am parent - 27318 
Waiting for child to finish 
--- I am child - 0 
Bye bye bye world 
Child finished, status 0 

然而,當線標記爲「注」被註釋,「再見」不執行,和睡眠被執行(3)。

$ ./hello 
Hello world 
I am parent - 27350 
Waiting for child to finish 
--- I am sleeping 
Child finished, status 2816 

有人可以幫我理解可能發生了什麼。我發現很奇怪,如果我用printf()替換「cout」,然後執行睡眠。

謝謝 艾哈邁德。

回答

1

根據the spec,參數列表到execl必須由一個NULL指針終止(即(char *)0,不"")。

更改附近的代碼只是改變當您調用execl時發生的事情。正如所寫,該程序的行爲是未定義的。

P.S.始終檢查庫例程的返回值是否存在錯誤。

0

exec系列函數成功時不返回。 這就是爲什麼當執行execl()時不會看到睡眠註釋的原因。