Zac Reynolds Zac Reynolds - 1 year ago 75
Linux Question

Make child process wait for parent

I have to write a program in C that will

a new process and then use that processes
for another function. However I need to call this function before the child process can run and I don't know how to do this.

Here's some pseudo code of what I'm trying to do.

pid_t pid = fork();
if(in_child){ //In the child process
//launch child application
//somehow stop the child application before it actually executes any code
//call my function with the child's pid
//resume the child process
//do other stuff

If you need any additional info please ask. Thanks.

Edit: I do not have access to the code for the child. I'm just wanting to run an executable.

Answer Source

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).