我希望我的子进程在我的 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/