fork() child process in background?

Hey Guys,

Is there any way we can fork the child process in background? Actually, when I googled it, I found two solutions: the first one explained that background child process does not have stdin, stdout, and stderr associated with it, and the other one said that, background child process does not have a parent?

I am not sure if any of these are true. Can someone please point me in the right direction?

Thanks
The child process, AFAIK, is just an exact copy of the parent process. So when you fork(), you're just recreating your process. I'm not sure where execution begins in the child process - I would assume, from the instruction directly after the fork, otherwise the process would keep forking ad infinitum and you'd have some kind of weird process overflow or something - but anyway, you can use stdout, stdin and stderr, just as you usualy would.

I'm not sure what your asking (although it's likely my knowledge doesn't stretch this far... very likely, in fact, as I didn't know what forking was three weeks ago...); it seems like you want to know whether you can have a child running without interaction from anything else. You can - fork() returns the PID of the process that was forked. If the PID is 0, you have the child process. If the PID is > 0 you have the parent process. If it's -1, then you have an error...

Consider the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
pid_t PID = fork();

switch (PID) {
    case -1:
        std::cerr << "Error!\n"
        break;
    case 0: // This is the child process
        std::cout << "Success! Child process created.\n";
        break;
    default: // Parent process
        std::cout << "PID: " << PID << "\n";
        break;
}


The output of that would be one of the following:
1.
Success! Child process created.
PID: 2

2.
PID: 2
Success! Child process created.

3.
Error!


I'm not sure what you're asking though; maybe someone else knows better.
Thanks for the reply chrisname, but actually I know how fork() works. What I am asking is, how can I put the child process in the background? Here is the example of running a process in background

$ date &
[1] 22735


Notice the &, which is to put the process in the background. Now I want to implement this same functionality programatically. Using system() is not an option.

Thanks once again
Oh! Sorry, I wasn't sure what you were asking.

I'm not sure about that... sorry.
All that "backgrounding" means in this context is that the shell does
not do a blocking waitpid() on the child process, but rather expects
a SIGCHLD when the child terminates.

Programatically, I am still not sure about where should I start doing this.
Having you considered doing POSIX threads?
Topic archived. No new replies allowed.