c - 在 C 中使用子进程的 exec 命令执行 bin 程序

标签 c process operating-system exec child-process

我希望我的子进程在我的 parent 等待 3 秒并杀死 child 时执行一个 bin 程序。傻我知道,但还是要这样做。在这里似乎无法正确使用 execv。我试过运行日历、gedit 等。只是对我没有用。有什么建议 ?

   int main(int argc, char* argv[])
   {
    pid_t pid;

    pid = fork();

    if (pid == 0) { 
      execv("calc",argv);
      return 0;
    }
    else if (pid > 0) { /* parent process */
      sleep(3);
      kill(pid, SIGKILL);
      printf("Child process with the ID: %d has been killed by the parent process with the ID: %d...\n", pid, getpid());
      return 0;
    }
}

最佳答案

来自 man execv:

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed.

所以 - 它不会搜索 PATH。您可以检查 execv 的返回值以查看它是否失败。

使用“/usr/bin/gedit”作为第一个参数,它应该可以工作。另请注意,在较旧的计算机上,三秒钟可能不足以让程序运行。

关于c - 在 C 中使用子进程的 exec 命令执行 bin 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35489955/

相关文章:

c - 如何在头文件中声明锯齿状数组?

c - pcap 过滤器表达式

c++ - 使用 extern "C"在 C 文件中调用 C++ 类函数

c - 文件描述符和文件指针有什么区别?

windows - SysInternals WinObj 设备列表机制

c - Netbeans C 程序返回值 2

java - 过程输出太大

c++ - 在 WinAPI 中为控制台应用程序处理窗口关闭事件的最简单方法是什么?

c++ - 等待子进程

algorithm - 分布式系统中的锁定数据结构