Search code examples
cforktty

Keep parent process in foreground after fork


I have a C program that forks a child process, which I'm running from a linux shell.

My problem is that, after forking, the parent process moves to the shell background. I would like the parent process to stay in the foreground.

Here is a simple example:

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

int main(void)
{
    int i;
    for (i = 0; i < 3; i++) {
        printf("Before Fork\n");
        sleep(1);
    }

    printf("forking...\n");
    pid_t pid = fork();
    if (pid) {
        // child
        printf("Child started and now exiting\n");
        exit(EXIT_SUCCESS);
    }

    // parent
    wait(NULL);
    for (i = 0; i < 3; i++) {
        printf("After Fork\n");
        sleep(1);
    }

    return 0;
}

Output (with comment added later)

Before Fork
Before Fork
Before Fork
forking...
Child started and now exiting
After Fork
gregp@gregp-ubuntu:~/fork_example$ After Fork       # <--- User returned to shell
After Fork

Notice that shortly after the fork, the user is returned to the shell prompt, and the program continues running in the background. I do not want this to happen. I want the program to continue running in the foreground.

Desired Output (with comment added later)

Before Fork
Before Fork
Before Fork
forking...
Child started and now exiting
After Fork
After Fork
After Fork
                 # Program now exits and user returns to shell
gregp@gregp-ubuntu:~/fork_example$

Solution

  • th pid is returned in the parent, so your condition should be

    if (!pid)
    

    because the child in your code will not go to the if. that's because

    On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.