Keep the parent process in the foreground after the fork

I have a C program that creates a child process that I run from linux shell.

My problem is that after forking, the parent process moves to the background of the shell. 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; } 

Conclusion (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 

Note that soon after fork, the user returns to the shell prompt, and the program continues to run in the background. I do not want this to happen. I want the program to continue to work in the foreground.

Desired result (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$ 
+4
source share
3 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 if. that since

If successful, the PID of the child process is returned in the parent, and 0 is returned in the child. On error -1 is returned to the parent, the child process is not created, and errno is set accordingly.

+4
source

Problem with adding

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

Immediate problem

Identified by other people - they get a loan, please.

The problem with the wait() loop is relevant only after you have fixed the if (pid) test ... It is interesting if you made a mistake if you wrote if (pid == 0) { // Child ? Probably no; you know fork() returns the PID of the child element to the parent element and zero to the child element. An explanation helps.

+2
source

fork () returns 0 to the child process on success.

If the loop will not be executed, if the condition is zero.

therefore, if the child wants to fulfill, you need to change if the condition in

 if(!pid) 

further details of man fork

+2
source

Source: https://habr.com/ru/post/1498474/


All Articles