c - 使用 execv 命令 fork 和执行

标签 c linux

在 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/

相关文章:

c - 如何使 Windows 控制台光标跳转到行尾的下一行

linux - 使用 perf probe 监控特定功能期间的性能统计信息

linux - 如何禁止打印到 CLI 的配置单元列名?

用C检查文件是否是纯文本

C++ 2 嵌套for循环转换为递归

c - 在没有任何临时变量的情况下在 O(n) 中排序

linux - 如何恢复损坏的 dnf 数据库?

linux - 在 Linux 脚本中接收 "curl: (3) Illegal characters found in URL"

c - 初始化结构体数组

c - 不确定 int regs = 0, i, *regs 是什么意思