在 Linux 中,我正在尝试创建一个 C 程序,它 fork 并创建 2 个 child (Child1 和 Child2)。每个 child 都在执行一个过程,即使用 execv 命令执行文件。这是创建两个文件 destination1.txt 和 destination2.txt 的父文件。这些文件的代码位于 Prcs_P1.c 和 Prcs_P2.c 中。它们是 C 文件。代码编译运行但不执行执行文件的操作。我究竟做错了什么?我缺少的部分是什么?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
pid child1, child2;
enter code here
child1 = fork();
errno = 0;
if (child1 < 0)
{
printf("Error! Forking can't be done\n");
}
else if (child1 == 0)
{
printf("Child one process activated! %d\n", getpid());
execv("Prcs_P1.c", NULL);
}
else
{
printf("Parent1 process activated! %d\n", getpid());
}
child2 = fork();
if (child2 < 0)
{
printf("Error! Forking can't be done\n");
}
else if (child2 == 0)
{
printf("Child two process activated! %d\n", getpid());
execv("Prcs_P2.c",NULL);
}
else
{
printf("Parent2 process activated! %d\n", getpid());
}
return 0;
输出是 Parent1 进程已激活! 2614 Parent2 进程已激活! 2614 子进程激活! 2615 Parent2 进程已激活! 2615 子二进程激活! 2617 子二进程激活! 2616
最佳答案
您不应将“.c”文件作为输入传递。它不可执行。您必须将可执行文件作为输入传递。类似“xxxxxx.out”的东西。
关于c - 使用 execv 命令 fork 和执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935324/