Saturn
Saturn

Reputation: 18159

Returning a value from the child process to its parent in C created with fork()

Learning about forking with C.

I can spawn a child process with fork() alright. Suppose that it performs some calculation. When the calculation is done, I'd like it to die and return the result (some int) to the parent. How can this be done?

Normally I'd post code of my progress, but that's literally it:

int main () {
    pid_t  pid = fork();
    if (pid == 0) {
        // I'm a child!
        int calculation = 10 + 10;
        // <----- Return 20 to the parent?
    }else{
        // I am the parent, and I am waiting to receive a 20
    }
    exit(0);
}

Upvotes: 0

Views: 599

Answers (2)

You cannot do that, because exit gives only an exit code (which conventionally should be EXIT_SUCCESS on success, and has only 7 bits). And the exit code is the only thing that a process returns (see waitpid(2), which you should always call to avoid zombie processes).

You could have parent and child process use some shared memory and semaphores (see shm_overview(7) & sem_overview(7)), but this is complex, so is inappropriate for your case.

The simplest -and probably fastest- way is just to use pipe(7)-s (to be set up before fork) and have the child process print on its stdout to the pipe and the parent process read on the pipe. See pipe(2) and also popen(3).

You might want to fork several (at most a dozen on a desktop) processes in parallel. Then you'll need to multiplex their pipes inputs. For that, have some event loop and use poll(2) in the parent process for the multiplexing.

Read also Advanced Linux Programming

Upvotes: 1

mrjoltcola
mrjoltcola

Reputation: 20862

Besides pipe and fork, the simplest method is to use popen() and read the childs response on stdout as FILE stream.

You dont have to deal with fork at all. (Though indeed, popen is implemented on top of fork and pipe and dup2).

pclose() can be used to check the exit status of child.

Upvotes: 1

Related Questions