Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep parent process in foreground after fork

Tags:

c

fork

tty

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$
like image 753
Greg Prisament Avatar asked Jun 04 '26 22:06

Greg Prisament


2 Answers

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.

like image 173
No Idea For Name Avatar answered Jun 06 '26 16:06

No Idea For Name


fork() return 0 to child process, on success.

If loop will not execute when condition is zero.

so if child want to execute you have to change if condition into

if(!pid)

further details man fork

like image 30
sujin Avatar answered Jun 06 '26 17:06

sujin