c++ - execl 不运行编程

标签 c++ c process exec

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

bye.cc

#include <iostream>

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

你好.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”,那么 sleep 就会执行。

谢谢, 艾哈迈德。

最佳答案

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

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

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

关于c++ - execl 不运行编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469803/

相关文章:

c - 将 char* 作为参数传递给动态调用的函数会产生运行时错误

c# - 为什么 Process.Start(string) 为 WMV 文件返回 null

c# MainWindowHandle 始终为零

c++ - 为什么我不能给这个 int 赋值?

从中缀转换为后缀时捕获堆栈中丢失的操作数或运算符

c++ - 将托管引用传递给采用非托管指针的方法

c - 链接器找不到 initgraph() 和 closegraph()?

linux - 带有信号的 Fork() 子进程

c++ - 使用表达式参数专门化模板

c++ - 在结构的 union 成员中使用 std::string 时无法引用默认构造函数