apson11
apson11

Reputation: 51

How to use the execl() function to execute a C program?

I have a C program that computes the next prime number after 100, I need to execute this program using execlp function. The prime number program and execlp function are both different files but are in the same directory. Any help is appreciated, below is my code for execlp function and my C program. I've already tried running the program using execlp, but it doesn't seem to work. I've included the path, the program to run and NULL as arguments.

//Main program, that runs execlp function
int main(int argc, char *argv[]) {
    int pid;
    int start=0;

    pid = fork();       /* fork a child process */

    if(pid > 0) {       /* parent continues here  */
        count(start, 'P');
        wait(NULL);     /* to get printing done before shell prompt */
    } else if(pid == 0) {    /* child got here */
        execlp("/home/student/Documents/FIT2100/PRAC3/", "./primeNum", 
NULL); /* execute primeNum program*/
    } else {            /* there is a problem with fork */
        perror("Failed to fork a process\n");
        exit(1);
    }
}
//Prime number program, filename is called primeNum.c
int main() {
    bool isPrime = false;
    int counter = 0;
    int inputNum;
    inputNum = 100;

    while(isPrime == false){
        inputNum += 1;

        for(int i = 1; i <= inputNum; i++){
            if(inputNum % i == 0){
                counter++;
            }
        }

        if(counter <= 2){
            isPrime = true;
        }
    }

    printf("Next prime after 100 is %d\n", inputNum);

}

Upvotes: 0

Views: 6686

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753775

The 'path' argument to execl() is the pathname of the executable, not the directory containing the executable. Making a guess, you probably need:

execlp("/home/student/Documents/FIT2100/PRAC3/primeNum", "primeNum", (char *)NULL);

The first argument is the absolute pathname of the program; the second is the string that will passed as argv[0]; the NULL (which should strictly be (char *)NULL or (char *)0 to avoid possible problems with #define NULL 0 — as shown) marks the end of the arguments. There's nothing to stop you using "pink elephant" as the argv[0] value if you want to.

A relative pathname is perfectly acceptable; if an open() call would find the executable file using the name, then it is OK for use with execl().

Upvotes: 1

Related Questions