我正在尝试编写一个程序,该程序将 fork ,然后打开一个文件并执行它。它应该执行的文件称为子文件,并且它已经被编译。当我输入 ./child 时,它就会运行。但是,当我运行该程序时,它不会执行子程序,并且系统会提示我输入“执行失败”中的错误消息。我做错了什么?
这是我的父类
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main (int argc, char **argv)
{
pid_t parent = getpid();
pid_t pid = fork();
if (pid == -1)
{
// error, failed to fork()
}
else if (pid > 0)
{
int status;
waitpid(pid, &status, 0);
}
else
{
int var = execvp("./child", NULL);
if(var < 0)
{
printf("Execution failed");
}
}
exit(0); // exec never returns
}
这就是 child
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv)
{
printf ("Im the child");
exit (0);
}
最佳答案
我真的不知道你做错了什么。经过复制和编译(以及一些警告提示)后,您的代码运行良好(GCC 7.2)。
显然,子进程必须位于运行主可执行文件( fork 的那个)的同一工作目录中。
但我可能会以这种方式编写代码,但我不是 fork 专家:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
extern int errno;
int main () {
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "%s\n", strerror(errno));
return 1;
}
if (pid == 0) {
int ret = execl("./child", "", (char *)NULL);
if(ret < 0) {
fprintf(stderr, "%s\n", strerror(errno));
return 1;
}
} else {
wait(NULL);
}
return 0;
}
至少它告诉您 execl
遇到了哪个错误。
关于无法让 execvp 执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201450/