我正在学习zeromq,有如下测试代码:
void *context = (void *)zmq_ctx_new();
if (context == NULL) {
printf("context is null\n");
} else {
printf("context was created successfully\n");
}
printf("connecting to the 0mq server\n");
void *responder = zmq_socket (context, ZMQ_REQ);
printf("got socket\n");
if (responder == NULL) {
printf("responder is null\n");
} else {
printf("responder was created successfully\n");
}
当我运行代码时,它会在调用 zmq_socket()
时崩溃。这是输出:
Starting 0mq server context was created successfully connecting to the 0mq server Segmentation fault (core dumped)
我不确定为什么 zmq_socket()
会失败。我试图在我的 Makefile 中的链接系列的开头移动 zmq 库。它仍然失败。
如有任何帮助,我们将不胜感激。
最佳答案
改变
void context = (void)zmq_ctx_new();
进入
void *context = (void *)zmq_ctx_new();
而且,当我尝试你的代码时,void context = (void) zmq_ctx_new() 会导致编译错误。
这是我的代码,可以在我的 OSX 上运行。
gcc -o cli client.c -lzmq
gcc -o srv server.c -lzmq
客户端.c:
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
int main (void)
{
printf ("Connecting to hello world server…\n");
void *context = (void *)zmq_ctx_new ();
void *requester = zmq_socket (context, ZMQ_REQ);
zmq_connect (requester, "tcp://localhost:5555");
int request_nbr;
for (request_nbr = 0; request_nbr != 10; request_nbr++) {
char buffer [10];
char snd[] = "hello";
printf ("Sending Hello %d…\n", request_nbr);
zmq_send (requester, snd, sizeof(snd), 0);
zmq_recv (requester, buffer, 10, 0);
printf ("Received World %d\n", request_nbr);
}
zmq_close (requester);
zmq_ctx_destroy (context);
return 0;
}
服务器.c:
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
int main (void)
{
// Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket (context, ZMQ_REP);
int rc = zmq_bind (responder, "tcp://*:5555");
assert (rc == 0);
while (1) {
int nrecv;
char buffer [10];
nrecv = zmq_recv (responder, buffer, 10, 0);
printf ("[%d] Received %s\n", nrecv, buffer);
sleep (1); // Do some 'work'
zmq_send (responder, "World", 5, 0);
}
return 0;
}
关于c - zmq_socket() 给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647158/