简体   繁体   中英

Using 'execlp' System Call to run current program recursively

I am trying to use execlp to call my program inside of my program (for a project) and am having trouble. I have created a sample project which should count down from n to 0 (essentially run n times). Each time I run it, I get the first decrement and then I get a seg fault. Please let me know what I am doing wrong here.

PS Fairly new to System calls in C, so explain thoroughly if possible. Thanks in advance!

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <time.h>

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

    int n = atoi(argv[1]);

    char newParameters[2];
    sprintf(newParameters, "%d", n - 1);

    if (n != 0)
    {
        execlp("./tmp", newParameters, (char *)NULL);
    }

    printf("The program has finished.\n");

    return 0;
}

The C program is called tmp.

From the execlp manual :

The initial argument for these functions is the name of a file that is to be executed.

The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed.

That is, the first argument to execlp is the executable file to run. The second parameter corresponds to argv[0] passed to main . The third parameter is argv[1] and so on. So the execlp in this case needs to be:

execlp("./tmp", "./tmp", newParameters, NULL);

Or better still use argv[0] rather than a hard coded executable name so that it can work no matter how the program is linked:

execlp(argv[0], argv[0], newParameters, NULL);

Other things to note:

  • newParameters can only hold a single character string (including NUL terminator). So any command line with a number greater than 9 will result in undefined behaviour.
  • Other good practices: Always check argc before using argv values and always check the return value of all function calls, specifically execlp in this case.

execlp(2) cannot be used to run a program recursively, because no new process is created. The current context (process address space, data, etc.) is loaded (overwritten) with the new mapping to execute the same program again, and the data segment, the stack and memory segments are detached and trashed to create the new ones. When this instance finally exit(2) s, there's no process backed up to return to. To create a new process you need to use fork(2) , not execlp(2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM