简体   繁体   中英

How to execute a program by fork and 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

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.

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