Question

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$
Was it helpful?

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.

OTHER TIPS

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

Incipient problem

You need a loop around the wait(). As written, it waits for one child to finish (ignoring the PID returned and not setting the status). The shell's wait command is different from the system call — but the code looks as though it was written by analogy with the shell's command.

Immediate problem

Identified by others first — they get the credit, please.

The wait() loop problem is only relevant after you've fixed the if (pid) test ... I wonder if you'd have made the mistake if you wrote if (pid == 0) { // Child? Probably not; you know the fork() returns the PID of the child to the parent and zero to the child. Explicitness helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top