Search code examples
cprocesscloneforksystem-calls

Calling a binary from C (whilst sharing file descriptors)


I'm playing around with sycalls, and have just written codes along the lines of

/* Clone the process and launch Something */
child_stack = (void *) malloc(max_memory);
args = malloc(2 * sizeof (int **));

args[0] = in_socket_fds;
args[1] = out_socket_fds;

clone(foo, child_stack + max_memory ,CLONE_FILES|CLONE_VM|CLONE_IO|CLONE_FS, (void *) args);

wait();

where the foo function is :

    int foo(int** args) {
     fprintf(stderr, "Hello world %d %d", args[0][0], ags[1][0]);
     _exit(0);
    }

What I'd really like to do is call a binary from the foo function.

    int foo(int** args) {
     system(start program foo)
     _exit(0);
    }

This binary should share the same file descriptor table (hence the use of clone previously). The code above is incorrect, since I don't think system allows to share the file descriptor table. ( I don't want copies of the fds, I really want to be able to read/write them) These fds are sockets.

    int foo(int** args) {
     system(start program foo)
     _exit(0);
    }

How can I make the clone command call a binary rather than a function? (is this even possible), or use the system call whilst sharing file descriptors?

Thanks


Solution

  • Go for fork() / execlp() instead of clone() / system(). A forked child inherits the file descriptors from the parent, and execlp() (or its relatives) allow you to load a different executable in the child.

    You probably could exec*() in the function called by clone() (see comments), but in this case the fork() semantics are much simpler.