Zmq_socket () gives segmentation fault
I am learning zeromq and have the following test code:
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");
}
When I run the code, it crashes when called zmq_socket()
. Here's the result:
Initial server context 0mq was successfully created to connect to Server 0mq Segmentation fault (kernel reset)
I'm not sure why it zmq_socket()
is failing. I tried to move the zmq library to the beginning of the link line in my Makefile. It still doesn't work.
Any help would be much appreciated.
+3
source to share
1 answer
change
void context = (void)zmq_ctx_new();
in
void *context = (void *)zmq_ctx_new();
And when I tried my code, void context = (void) zmq_ctx_new () will throw a compilation error.
here is my code that might work on my 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;
}
0
source to share