libuv简单回显客户端

时间:2015-03-29 15:24:56

标签: c libuv

我尝试使用unix管道为以下示例代码开发一个简单的echo客户端:https://github.com/nikhilm/uvbook/blob/master/code/pipe-echo-server/main.c

这是我的客户代码:

#include <uv.h>
#include <stdio.h>
#include <stdlib.h>

void OnConnect(uv_connect_t* connect, int status){
  printf("Hi!");
}

int main(){
  uv_pipe_t* handle = (uv_pipe_t*)malloc(sizeof(uv_pipe_t));
  uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t));

  uv_pipe_open(handle, socket(PF_UNIX, SOCK_STREAM, 0));

  int r;
  uv_pipe_connect(connect, handle, "echo.sock", OnConnect);
  uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

但是一旦我运行它,就会出现段错误。服务器确实给我一个进程已连接的消息。来自GDB的回溯:

Program received signal SIGSEGV, Segmentation fault.
uv__io_start (loop=0x0, w=w@entry=0x602098, events=events@entry=5)
    at src/unix/core.c:787
787     src/unix/core.c: No such file or directory.
(gdb) backtrace full
#0  uv__io_start (loop=0x0, w=w@entry=0x602098, events=events@entry=5)
    at src/unix/core.c:787
        __PRETTY_FUNCTION__ = "uv__io_start"
#1  0x00007ffff7bc7ed8 in uv_pipe_connect (req=0x602120, handle=0x602010, 
    name=<optimized out>, cb=0x400870 <OnConnect>) at src/unix/pipe.c:188
        saddr = {sun_family = 1, 
          sun_path = "echo.sock", '\000' <repeats 98 times>}
        new_sock = 0
---Type <return> to continue, or q <return> to quit---
        err = <optimized out>
        r = <optimized out>
#2  0x0000000000400918 in main () at client.c:16
        handle = 0x602010
        connect = 0x602120
        r = 0

1 个答案:

答案 0 :(得分:4)

在允许使用之前,您需要初始化管道句柄。

uv_pipe_open之前添加此行: uv_pipe_init(uv_default_loop(), handle, 0);

另外,casting the result of malloc is unnecessary