Skip to content
Advertisement

libuv: difference between fork and uv_spawn?

Recently I have been playing around with Libuv. I don’t get the programming model as far as child processes are concerned. For example look at the following code:

uv_loop_t *loop;
uv_process_t child_req;
uv_process_options_t options;

void on_exit(uv_process_t* proc, long int io, int hj)
{
        std::cout<<"on exit call back"<<std::endl;
}

int main() 
{
    loop = uv_default_loop();

    char* args[3];
    args[0] = "mkdir";
    args[1] = "test-dir";
    args[2] = NULL;

    options.exit_cb = on_exit;
    options.file = "mkdir";
    options.args = args;

    int r;
    r = uv_spawn(loop, &child_req, &options);
    std::cout<<r<<std::endl;
    if (r) {
            std::cout<<"from line 231"<<std::endl;
        fprintf(stderr, "%sn", uv_strerror(r));
        return 1;
    } else {
        fprintf(stderr, "Launched process with ID %dn", child_req.pid);
    }

    return uv_run(loop, UV_RUN_DEFAULT);
}

Here the output printed on console is:

0
Launched process with ID 511168
on exit call back

In my understanding uv_spawn acts like fork(). In child process the value of r is 0 and in parent process it is non-zero. So from line 231 should also be printed. But evidently it is not. I read the documentation end to end but I have no clue. Any help will be appreciated.

Advertisement

Answer

n my understanding uv_spawn acts like fork()

And then like execve and child becomes mkdir. So child executes mkdir, and only parent returns to your code.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement