-
-
Save rkanavath/1fc0ecbe89e320b045ea5ec64e0a83fb to your computer and use it in GitHub Desktop.
zeromq forking - child process terminates inherited zeromq context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.c | |
// zmq-test1 | |
// | |
// Created by Matt Connolly on 8/08/2013. | |
// | |
//#include <ZeroMQ/zmq.h> | |
#include <czmq.h> | |
const char* address = "tcp://127.0.0.1:6571"; | |
void my_handler(int, siginfo_t *info, void *uap); | |
zctx_t* context; | |
int main(int argc, const char * argv[]) | |
{ | |
int rc; | |
printf("parent process: %d\n", getpid()); | |
struct sigaction action; | |
action.sa_flags = SA_SIGINFO; | |
action.sa_mask = 0; | |
sigemptyset(&action.sa_mask); | |
action.sa_sigaction = &my_handler; | |
// action.sa_sigaction = NULL; | |
rc = sigaction(SIGCHLD, &action, NULL); | |
assert(rc == 0); | |
context = zctx_new(); | |
void* sock = zsocket_new(context, ZMQ_PULL); | |
zsocket_bind(sock, address); | |
// ensure io threads are running before fork | |
sleep(1); | |
pid_t child_pid = fork(); | |
if (child_pid == 0) | |
{ | |
// child process | |
printf("child: process id = %d\n", (int)getpid()); | |
sleep(1); | |
zctx_destroy(&context); | |
printf("child: destroyed context inherited from parent\n"); | |
sleep(1); | |
void* ctx2 = zmq_ctx_new(); | |
void* sock = zmq_socket(ctx2, ZMQ_PUSH); | |
zmq_connect(sock, address); | |
const char* message = "hello"; | |
int i; | |
for (i = 0; i < 9; i += 1) { | |
printf("child: send message\n"); | |
zmq_send(sock, message, strlen(message), 0); | |
usleep(1); | |
} | |
zmq_close(sock); | |
zmq_ctx_destroy(ctx2); | |
printf("child: destroyed child context\n"); | |
printf("child: done\n"); | |
exit(0); | |
} | |
else | |
{ | |
// parent process | |
char* buffer; | |
zframe_t* frame; | |
int i = 0; | |
int received_count = 0; | |
while (received_count < 3) | |
{ | |
printf("parent waiting for message #%d...\n", i++); | |
frame = zframe_recv(sock); | |
if (frame) { | |
received_count += 1; | |
buffer = zframe_strdup(frame); | |
printf("Received: %s\n", buffer); | |
free(buffer); | |
zframe_destroy(&frame); | |
} | |
else { | |
printf("recv interrupted!\n"); | |
} | |
} | |
printf("parent: closing socket\n"); | |
zsocket_destroy(context, sock); | |
zctx_destroy(&context); | |
printf("parent: done\n"); | |
} | |
return 0; | |
} | |
void my_handler(int signal, siginfo_t *info, void *uap) | |
{ | |
printf("signal %d received, from child pid %d!\n", signal, info->si_pid); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment