我正在学习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()
时崩溃。这是输出:
启动0mq服务器上下文创建成功连接到 0mq服务器分段故障(核心转储)
我不确定zmq_socket()
失败的原因。我试图在我的Makefile中的链接系列的开头移动zmq库。它仍然失败。
任何帮助都将受到高度赞赏。
答案 0 :(得分:0)
变化
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
client.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;
}
server.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;
}