C++ fork() 和 execv() 问题

标签 c++ linux fork execv

我是 C++ 的新手,正在 Linux 上开发一个简单的程序,该程序应该调用同一目录中的另一个程序并获取被调用程序的输出,而不在控制台上显示被调用程序的输出。这是我正在处理的代码片段:

    pid_t pid;
    cout<<"General sentance:"<<endl<<sentence<<endl;
    cout<<"==============================="<<endl;
    //int i=system("./Satzoo");
    if(pid=fork()<0)
        cout<<"Process could not be created..."<<endl;
    else
    {
        cout<<pid<<endl;
        execv("./Satzoo",NULL);
    }
    cout<<"General sentance:"<<endl<<sentence<<endl;
    cout<<"==============================="<<endl;

我遇到的一个问题是,我能够在控制台上打印前两行,但无法打印后两行。我认为当我调用 Satzoo 程序时该程序停止工作。 另一件事是这段代码调用了两次 Satzoo 程序,我不知道为什么?我可以在屏幕上看到两次输出。另一方面,如果我使用 system() 而不是 execv(),那么 Satzoo 只工作一次。

我还没有想出如何在我的程序中读取 Satzoo 的输出。

感谢任何帮助。

谢谢

最佳答案

调用 fork() 后,您无法区分子进程和父进程。因此,子进程和父进程都运行 execv(),因此它们各自的进程镜像被替换。

你想要更像是:

pid_t pid;
printf("before fork\n");

if((pid = fork()) < 0)
{
  printf("an error occurred while forking\n");
}
else if(pid == 0)
{
  /* this is the child */
  printf("the child's pid is: %d\n", getpid());
  execv("./Satzoo",NULL);
  printf("if this line is printed then execv failed\n");
}
else
{
  /* this is the parent */
  printf("parent continues execution\n");
}

关于C++ fork() 和 execv() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586286/

相关文章:

c++ - 如果在堆上创建 vector ,是否意味着我可以从任何其他函数访问它?怎么样?

linux - x86 指令格式 : "ba 0e 00 00 00" . .. "mov $0xe,%edx"

c++ - 同步父子以从没有信号量的文件中读取

c++ - 如何找到程序的 main(...) 函数?

c++ - 如何实现符合标准的迭代器/容器?

c++ - push_back 如何在 STL vector 中实现?

node.js - USB-to-RS485 使用 Nodejs

c - Ncurses 鼠标滚轮向上滚动

c - fork 和执行

澄清 Pipe() 和 dup2() 在 C 中如何工作