libuv::进程

对于基于事件(event-based)的程序来说, 有个限制,没办法很好地利用多核,提高CPU使用率.
即使能够使用多线程编程来分发 handle, 但是每个 loop 还是只有一个线程.
这时候, 使用多进程就能够分担 loop 的压力,并且通过多进程
+ 通信的方法, 会比 多线程 + 共享内存的方法更加安全, 易于开发.

 

#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <libuv/uv.h>

void on_exit(uv_process_t* req, int64_t exit_status, int term_signal) {
    printf("exit_status = %lld , signal = %d\n", exit_status, term_signal);
    uv_close((uv_handle_t*)req, NULL);
}

int main() {
    uv_loop_t* loop = uv_default_loop();

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

    uv_process_options_t options;
    options.exit_cb = on_exit;
    options.file = "mkdir";
    //子进程就与父进程脱离了关系.
    options.flags = UV_PROCESS_DETACHED;
    options.args = args;


    //创建子进程,子线程创建一个文件夹
    int r;
    uv_process_t child_req;
    if ((r = uv_spawn(loop, &child_req, &options))) {
        printf("%s\n", uv_strerror(r));
        return 1;
    }
    else {
        printf(" child process ID =  %d\n", child_req.pid);
    }
    return uv_run(loop, UV_RUN_DEFAULT);
}

 

posted @ 2020-12-06 16:21  osbreak  阅读(268)  评论(0编辑  收藏  举报