Search code examples
csignalsforkexec

Runing Parent Process code only after suspending child


I have a process P1. I am creating a child by fork ,and then exec inside the child's portion of the fork. I want to suspend the child and then execute the rest of the parent code ONLY after the child is suspended . Any Idea how can i do that?

int pid=fork();
if(pid==0)
{ 
    //Do something in here
 } 
else 

{ suspend the child and do something else ,only after the child is suspended }


Solution

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