c++ - 意外的 fork 行为

标签 c++ linux fork execvp

我有一个无限期运行的程序。出于测试目的,我制作了一个包装程序,它在指定的时间后杀死另一个程序(通过命令行/终端参数指定)。被 fork 的程序需要传递两个同名的文件夹(我无法控制这个),所以我只是将相同的参数传递给它两次,如下所示:

pid_t pid = fork();
if(pid == 0)
{
    //build the execution string
    char* test[2];
    test[0] = argv[2];
    test[1] = argv[2];
    test[2] = NULL;
    cout << "test[0] is " << test[0] << endl;
    cout << "test[1] is " << test[1] << endl;
    cout << "argv[1] is " << argv[1] << endl;
    execvp(argv[1],test);
}

问题是在 argv[1] 中传递的程序保持段错误。如果我通过终端自行调用它,它可以毫无问题地运行。在这两种情况下,我都传递了相同的文件夹。谁能告诉我为什么它对 execvp 不起作用?

我应该提到一位同事也在他的计算机上运行它,第一次运行良好,但之后每次都会出现段错误。

编辑:我添加了一个空术语来测试,但是,这并没有解决问题。

命令的形式完全是:

<executable> <wrapped prog> <folder> <duration>

在相对路径中它是:

Intel/debug/Tester.exe <program> test 10

最佳答案

如果数组的长度是静态的,你可能会更好

execlp

execlp(argv[1], argv[1], argv[2], argv[2], (char*)0);

对于execvp,数组应该以可执行文件的名称开始,以NULL结束。

执行器

char* args[] = { argv[1], argv[2], argv[2], NULL };
execvp(argv[1], args);

超时运行

无论如何,如果你想要的只是一个简单的包装器,它运行一个带超时的子进程,那么你的程序可能会非常简单和通用,只要你愿意从超时参数开始:

/*runWithTimeout.c
  compile with: make runWithTimeout
  run with: ./runWithTimeout seconds program arguments...
*/
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>

int main(int argc, char** argv)
{
  assert(argc >= 1+2);
  int pid, status = 1;
  if((pid = fork()) == 0) {
    alarm(atoi(argv[1]));
    execvp(argv[2], argv + 2); 
    /*^the child ends here if execvp succeeds,
    otherwise fall-through and return the default error status of 1
    (once in child (which has no one to wait on) and 
    then in the parent (which gets the status from the child))*/
    perror("Couldn't exec");
  }else if(pid < 0){ perror("Couldn't fork"); };
  wait(&status);
  return status;
}

关于c++ - 意外的 fork 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655226/

相关文章:

Android OpenCV颜色分割显示在ImageView上

c++ - VisualStudio- fatal error LNK1168 : cannot open myfile.exe for writing

c++ - 停止共享库链接以删除未使用的类

c++ - Windows 与 Linux GCC argv[0] 值

c - execvp 新进程镜像并退出

c# - 将内核链接在一起时值随机变化

c++ - C++语法和编译器错误-运算符<<不匹配

linux - 递归重命名所有子目录中的 .jpg 文件

ruby - Ruby 中的写时复制 fork

将系统的使用更改为 C 中的 Fork 和 exec