2

Is it possible to use the clone() system call in order to run a new program, in a similar way that the usual fork() + exec() combination works?

I've already read The difference between fork(), vfork(), exec() and clone() and the man page, but it is still not enough for me to understand if such thing is possible

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
user612575
  • 21
  • 2
  • 1
    You're probably actually wanting `posix_spawn()`. – Shawn May 02 '19 at 21:44
  • I recognize that you claim already to have read the dupe target, but there really isn't much more to say. `clone()` has the effects it is documented to have, which are well summarized by that question *and* its answers. – John Bollinger May 02 '19 at 22:30

2 Answers2

1

I'm using my own spawn function and on Linux I'm using clone with something like:

#define _GNU_SOURCE
#include <unistd.h>
#include <sched.h>
#include <signal.h>
pid_t run_kid(int Kid(void *), void *Arg, _Bool VForkEh)
{
    #if __linux__
    if(VForkEh){
        char stack[1<<13];
        return clone(Kid,stack+sizeof stack,
                CLONE_VM|CLONE_VFORK|CLONE_CHILD_SETTID|SIGCHLD,
                Arg, (void*)0/*partid,*/, (void*)0/*tls*/, (void*)0);
    }
    #endif
    pid_t r; if (0==(r=fork())) _exit(Kid(Arg));
    return r;
}

If you compile it on Linux and call it with VforkEh=1, it will call clone and execute the Kid hook in the child while the parent is suspended as with vfork (but without the problems of vfork because of the dedicated stack).

You should then be able to execve from the child, but keep in mind that because of the vfork semantics, the memory of the parent and the child will be shared so you should avoid async-unsafe functions and undo errno modifications if any.

http://git.musl-libc.org uses clone in as similar way to implement posix_spawn (but it doesn't have to undo errno-changes because it can use raw syscalls that don't set errno at all).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
0

clone is like fork except that the child ecexution context is constrained to a single function, you can used clone like fork you'd need pass any values needed by the child process to the child function.

You'd probably still need exec in the child function.

Jasen
  • 11,837
  • 2
  • 30
  • 48