Search code examples
clibuv

libuv simple echo client


I'm trying to develop a simple echo client using unix pipes for the following example code: https://github.com/nikhilm/uvbook/blob/master/code/pipe-echo-server/main.c

this is my client code:

#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);
}

But as soon as I run it, it segfaults. The server does give me a message that a process has connected. A backtrace from 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

Solution

  • You need to initialize the pipe handle before you are allowed to use it.

    Add this line before uv_pipe_open: uv_pipe_init(uv_default_loop(), handle, 0);

    Also, casting the result of malloc is unnecessary.