Search code examples
coperating-systemexec

Exec function in c is not running


This is not running on my Mac for some reasons that I can't figure out. the output I am getting is only from the main.c the output is

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

I need the main.c to execute counter.c and pass the argument 5 which I will then have to use it inside the for a loop, but I can't get exec to run at all no matter what path I put.

//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);
    }
}

Solution

  • In a comment, you mention you compile counter.c into an executable called a.out. This is the default executable name when you do not provide an output name explicitly to the compiler. Thus, if you compile both counter.c and main.c, only one of them will be the a.out.

    You can provide gcc an option to name your executable different from the default:

    gcc -o counter counter.c

    Also, your invocation of execl is not quite correct. The first argument is the path to the executable, but the remaining arguments will become argv[0], argv[1], etc. Thus, you really want to invoke execl this way:

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