Skip to content
Advertisement

C – program is terminated (fork() and exec())

I have the following code:

int main(int argc, char **argv)
{
    char    *program;
    char     stringa[1000] = "";
    int num = 123;
    char snum[5];

    program = argv[1];

    sprintf(stringa, "./%s", program);

    pid_t pid = fork();
    if (pid < 0 ) {
        perror("fork failed."); 
        exit(1); }

    else if (pid == 0) {
        char* args[] = {stringa, NULL};
        execv(args[0], args);
    }

    else {
        char procmon_str[] = "./procmon ";
        num = pid;
        sprintf(snum, "%d",num);
        printf("PID of child is %s", snum);

        char* args2[] = {procmon_str, snum, NULL};
        execv(args2[0], args2);

        sleep(20);
        kill(num, SIGTERM);

        sleep(2);
        int parent_pid = getpid(); 
        printf("PID of parent is %d", parent_pid);
        kill(parent_pid, SIGTERM);

    }

    wait(NULL);

    return 0;
}

The idea is to call with program with 1 command line argument which is a name of another compiled C program in the same folder. I want to execute that program from within the C code (hence the use of fork()), and at the same time i want to launch another program from within the parent part of the fork().

The part that is in the child part of fork() works perfectly, but when i run it through the shell it says Terminated right after and does not execute the code in the parent part of the fork().

Why is that?

Advertisement

Answer

  1. Your program call fork(). Now the execution of the parent process and the child process proceeds in parallel.

  2. The child:

    • Builds the argument array args[].
    • Calls execv() and is replaced by the program supplied as argument.
  3. The parent, in parallel with the child:

    • Builds the argument array args2[].
    • Calls execv() and is replaced by ./procmon.

The code from sleep(20) onwards in not reached unless the execv() fails (which you did not check for).

Read the manual page for fork() again, and redo the logic of the program.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement