Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a program by fork and exec

Tags:

c

linux

exec

I have a binary file that contains a program with function written in C inside that looks like:

int main()
{
    int a, b;
    foo(a,b);
    return 0;
}

And now I want to execute that program by using fork() and execve() in another program called "solver".

int main(int argc, char* argv[])
{
     pid_t process;
     process = fork();
     if(process==0)
     {
         if(execve(argv[0], (char**)argv, NULL) == -1)
         printf("The process could not be started\n");
     }
     return 0;
}

Is that a good way? Because it compiles, but I'm not sure whether the arguments of function inside "worker" program receive variables passed by command line to "solver" program

like image 652
Michał Habigier Avatar asked Feb 17 '26 22:02

Michał Habigier


1 Answers

I believe you are trying to achieve something like that:

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

static char *sub_process_name = "./work";

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

    process = fork();

    if (process < 0)
    {
        // fork() failed.
        perror("fork");
        return 2;
    }

    if (process == 0)
    {
        // sub-process
        argv[0] = sub_process_name; // Just need to change where argv[0] points to.
        execv(argv[0], argv);
        perror("execv"); // Ne need to check execv() return value. If it returns, you know it failed.
        return 2;
    }

    int status;
    pid_t wait_result;

    while ((wait_result = wait(&status)) != -1)
    {
        printf("Process %lu returned result: %d\n", (unsigned long) wait_result, status);
    }

    printf("All children have finished.\n");

    return 0;
}

./work will be launched with the same arguments as your original program.

like image 191
jdarthenay Avatar answered Feb 19 '26 10:02

jdarthenay