Sheri Sheri - 10 months ago 65
C Question

How to run multiple copies of another program - C

I have 2 files file1.c and file2.c
I want to run multiple copies of file1.c From My main file file2.c

Answer Source

Check the system calls fork() and exec(). A fork allows to copy the current process and all its memory. An exec call allows to replace to code to execute for the current process.

Basically, from your main process, you would fork multiple times. If the result of fork is 0, call exec with the command line for your child process.

int i;
for (i = 0; i < 10; i++) {
    // fork() returns 0 for the child process, 
    // and the actual pid of the new process for the parent process.
    pid_t pid = fork();

    if (!pid) {
        // This if will be executed only by the child process.

        // execvp() first argument is the executable file,
        // the second argument is a varargs for each arguments of the command line.

However, for this to work, both c files must be compiled into executables.