c - 使用 fork() 在 C 中创建两个子进程时出现问题(在 Debian 中)

标签 c process debian fork

尝试将父进程拆分为两个子进程。第一个将计算给定数字的阶乘。第二个只会说 I'm child 2!完成后,第一个子级将输出计算阶乘所需的时间。让第一个 child split 并完成其工作效果很好。然而,我看不出让老二做任何事。知道我做错了什么吗?

#include <stdio.h>
#include <time.h>
//#include </sts/types.h>
#include <unistd.h>

//prototypes
int rfact(int n);
int temp = 0;

main()
{
    int n = 0;
    long i = 0;
    double result = 0.0;
    clock_t t;
    printf("Enter a value for n: ");
    scanf("%i", &n);

    pid_t pID = fork();
    if (pID ==0)//child
    {
        //get current time
        t = clock();

        //process factorial 2 million times
        for(i=0; i<2000000; i++)
        {
            rfact(n);
        }

        //get total time spent in the loop
        result = ((double)(clock() - t))/CLOCKS_PER_SEC;

        //print result
        printf("runtime=%.2f seconds\n", result);
    }
    else if(pID < 0)
    {
        printf("fork() has failed");
    }
    else //parent
    {
        //second fork for child 2
        pid_t pID2 = fork();
        if (pID2 == 0)
        {
            execl("child2.o","child2", 20, NULL);
        }
        else if (pID2 < 0)
        {
            printf("fork() has failed");
        }
        else
        {
            waitpid(0);
        }
        waitpid(0);
    }
}

//factorial calculation
int rfact(int n)
{
    if (n<=0)
    {
        return 1;
    }
    return n * rfact(n-1);
}

这是 child2.c:

#include <stdio.h>

void main()
{
    printf("I'm child 2!");
}

好吧,我在使用 Eclipse 时遇到了问题。我删除了它并重新编译了两个 .c 文件。我使用 execl 指向 child2.o,但它仍然没有执行任何操作

最佳答案

您无法执行 .c 源文件! 您需要编译它并执行生成的二进制文件。

使用脚本语言,通常可以在开头添加 #!/usr/bin/whatever 行,它们将使用该解释器执行,但 C 需要编译,不能被解释。

关于c - 使用 fork() 在 C 中创建两个子进程时出现问题(在 Debian 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079122/

相关文章:

java - 为什么我们在启动 jvm 时指定最小和最大堆内存

ssh - Aptana SFTP key 交换

windows - 是否存在 ReadProcessMemory 失败的情况?

c - gnu c引用手册在哪个debian/ubuntu软件包中?

java - Hadoop 2.7.3 WARN util.NativeCodeLoader : Unable to load native-hadoop library for your platform. .. 在适用的情况下使用内置 java 类

c++ - 预处理器 token 扩展

c - 这是使用 Torch 从 LuaJit 解析 'Not enough memory' 的实用方法吗

c - C 中的消息传递/从 C 中的结构打印 char 数组

c - MinGW 海湾合作委员会 : "Unknown conversion type character ' h'"(snprintf)

java - 我怎样才能在 stdout/stderr 准备就绪时进行回调而不是忙于轮询?