gpt4 book ai didi

c - libuv 简单的 echo 客户端

转载 作者:行者123 更新时间:2023-12-02 21:18:00 26 4
gpt4 key购买 nike

我正在尝试使用 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

最佳答案

您需要先初始化管道句柄,然后才能使用它。

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

此外,casting the result of malloc is unnecessary .

关于c - libuv 简单的 echo 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29330958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com