c 中的 Exec 函数不是 运行

Exec function in c is not running

由于某些我无法弄清楚的原因,这不是我 Mac 上的 运行ning。我得到的输出仅来自 main.c 输出是

Parent PID 4066
Child PID 4067
Process 4067 exited with status 5

我需要 main.c 来执行 counter.c 并传递参数 5,然后我必须在 for 循环中使用它,但我无法执行到 运行 不管我放什么路径。

//main.c

int main(int argc, char *argv[]) {

    pid_t childOrZero = fork();

    if (childOrZero < 0){
        perror("Error happened while trying to fork\n");
        exit(-1);
    }


    if (childOrZero == 0){
        printf("Child PID %d\n", (int)getpid());
        execl("./counter", "5", NULL);
        exit(5);
    }

    // THis must be parent
    printf("Parent PID %d\n", (int)getpid());
    int status = 0;
    pid_t childpid = wait(&status);
    int childReturnedValue = WEXITSTATUS(status);
    printf("Process %d exited with status %d\n", (int)childOrZero, childReturnedValue);

    return 0;
}

counter.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main (int argc, char *argv[]){
    for (int i = 0; i<5; i++){
        printf("Process: %d  %d\n", (int)getpid(),i);
        //sleep(3);
    }
}

阅读documentation of execl for MacOSX and the POSIX specification of execl

它可能会失败(这是返回时的唯一情况)。所以代码:

if (childOrZero == 0){
    printf("Child PID %d\n", (int)getpid());
    execl("./counter", "5", NULL);
    perror("execl counter");
    exit(5);
}

在评论中,您提到您将 counter.c 编译成一个名为 a.out 的可执行文件。当您没有向编译器显式提供输出名称时,这是默认的可执行文件名称。因此,如果您同时编译 counter.cmain.c,其中只有一个是 a.out.

您可以提供 gcc 一个选项来命名不同于默认名称的可执行文件:

gcc -o counter counter.c

此外,您对 execl 的调用也不完全正确。第一个参数是可执行文件的路径,但其余参数将变为 argv[0]argv[1] 等。因此,您确实希望以这种方式调用 execl

     execl("./counter", "counter", "5", NULL);