【问题标题】:execl not running programmingexecl没有运行程序
【发布时间】:2015-02-12 05:13:01
【问题描述】:

我有以下两个简单的程序:

再见.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”的行启用(未注释),我会得到预期的行为,sleep(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

但是,当注释标记为“Note”的行时,不会执行“bye”,而是执行 sleep(3)。

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

有人可以帮助我了解可能发生的情况。我发现很奇怪,如果我用 printf() 替换“cout”,那么就会执行睡眠。

谢谢, 艾哈迈德。

【问题讨论】:

    标签: c++ c process exec


    【解决方案1】:

    根据the specexecl 的参数列表必须以 NULL 指针终止(即(char *)0,而不是"")。

    更改附近的代码只是更改调用execl 时堆栈上发生的内容。正如所写,程序的行为是未定义的。

    附:始终检查库例程的返回值是否有错误。

    【讨论】:

      【解决方案2】:

      exec 系列函数,成功时不返回。 这就是为什么执行 execl() 时看不到睡眠注释的原因。

      【讨论】:

        猜你喜欢
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多