If you mean any code at all, that can be difficult. You can use clone
with CLONE_STOPPED
instead of fork
to start the application into a stopped state (needing SIGCONT to get it going again).
However, if you simply mean specific code in the child and you can modify the child code, you can, as the first thing in main
, simply set up a handler for a USR1
signal (any IPC would probably do but a signal seems the simplest in this particular case) and then wait for it to fire before carrying on.
That way, the process itself will be running but won't be doing anything yet.
You then have the parent weave whatever magic it needs to do, then send a SIGUSR1 to the child.
But since, according to a comment, you don't have access to the client code, the first option may be the best, assuming that SIGCONT
won't actually cause problems with the child. That will require testing.
Of course, one thing to keep in mind is that neither clone()
nor fork()
will actually load your new program into the child process, that has to be done with an exec
-type call after the split. This is a result of the UNIX split between fork
and exec
functionality, detailed here.
That means that, while you don't control the child program, you do control the child process, so your code can wait for whatever signal it wants before loading up the new child program. Hence it's doable even with just fork()
.
Unfortunately, that also means that neither clone
nor fork
can stop your process after the new program has been loaded with exec
(at least not deterministically) so, if the fiddling you want to do is to the new program (such as manipulating its variables by attaching to its memory), you can't do it.
The best you can do is to fiddle with the new process while it still has a copy of the old program (before the exec
).