2015-02-12 132 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()时不会看到睡眠注释的原因。