Runing Parent Process code only after suspending child

In my opinion, the simplest sync mechanism is a simple pipe. If you want the child to wait before it execs, have it block on a read. eg:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char **argv)
{
        int p1[2];
        int c;
        if( pipe(p1)) {
                perror("pipe");
                return EXIT_FAILURE;
        }
        switch( fork() ) {
        case -1:
                perror("fork");
                return EXIT_FAILURE;
        case 0:
                read(p1[0], &c, 1); /* wait on the parent */
                close(p1[0]);
                close(p1[1]);
                execlp("echo", "echo", "foo", NULL);
                perror("exec");
                return EXIT_FAILURE;
        default:
                puts("This will always print first");
                fflush(stdout);
                write(p1[1], &c, 1); /* tell the child to continue */
                close(p1[1]);
                close(p1[0]);
        }
        return EXIT_SUCCESS;
}

If you want the child to exec before you suspend it, you could try sending SIGSTOP and make it continue with SIGCONT, but there’s really no point. If you do that, you have no way of knowing when the child will stop and it may run to completion before you even send the SIGSTOP. If you have some other external synchronization method (eg, the child is writing to the file system and you can monitor that), you should use that to make the child suspend itself. Trying to use SIGSTOP/SIGCONT will have numerous race conditions that you’ll need to deal with anyway. The best bet is to delay exec with something like the above.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top