コード例 #1
0
ファイル: rep.c プロジェクト: hbfhaapy/study
int 
main(int argc, char* argv[])
{
  char buf[128];
  void* ctx = zmq_ctx_new();
  void* rep = zmq_socket(ctx, ZMQ_REP);
  zmq_bind(rep, "tcp://*:5555");

  fprintf(stdout, "server init success ...\n");
  s_catch_signals();
  while (1) {
    memset(buf, 0, sizeof(buf));
    zmq_recv(rep, buf, sizeof(buf), 0);

    if (s_interrupted) {
      fprintf(stdout, "W: interrupt recevied, killing server ...\n");
      break;
    }
  }

  zmq_close(rep);
  zmq_ctx_destroy(ctx);

  return 0;
}
コード例 #2
0
 bool ServerZMQ::_onInit(TUInt port)
 {
     //init zmq
     m_context = zmq_ctx_new();
     if (m_context == 0)
     {
         zmqlog("Error occurred during zmq_ctx_new()");
         return false;
     } 
     
     m_socket = zmq_socket(m_context, ZMQ_PUB);
     if (m_socket == 0)
     {
         zmqlog("Error occurred during zmq_socket()");
         clear();
         return false;
     } 
     
     //bind to chosen port
     TChar address[100] = {'\0'};
     sprintf(address, "tcp://*:%u", port);
     int result = zmq_bind(m_socket, address);
     if (result != 0)
     {
         zmqlog("Error occurred during zmq_bind()");
         clear();
         return false;
     }
     
     //init signal handler
     s_catch_signals();
     return true;
 }
コード例 #3
0
ファイル: interrupt.c プロジェクト: a524631266/Ongoing-Study
int main(void)
{
    void *context = zmq_ctx_new();
    void *socket = zmq_socket(context, ZMQ_REP);
    zmq_bind(socket, "tcp://*:5555");

    s_catch_signals();
#if 1
    while (1) {
        // Blocking read will exit on a signal
        char buffer[255];
        zmq_recv(socket, buffer, 255, 0);
        if (s_interrupted) {
            printf("W: interrupt received, killing server...\n");
            break;
        }
    }
#else
    while (!s_interrupted) {
        char *message = s_recv(socket);
        if (!message) {
            break;
        }
    }
#endif

    zmq_close(socket);
    zmq_ctx_destroy(context);

#ifdef _MSC_VER
    system("pause");
#endif
    return 0;
}
コード例 #4
0
ファイル: interrupt.c プロジェクト: hnkien/0MQ_examples
void s_catch_signals () {
    struct sigaction action = {
        .sa_handler = s_signalhandler,
        .sa_flags = 0
    };
    sigemptyset(&action.sa_mask);
    sigaction(SIGINT, &action, NULL);
    sigaction(SIGTERM, &action, NULL);
}

int main () {
    void* context = zmq_ctx_new();
    void* socket = zmq_socket(context, ZMQ_REP);
    zmq_bind(socket, "tcp://*:5555");

    s_catch_signals();
    while(1) {
        // Blocking read will exit on a signal
        zmq_msg_t message;
        zmq_msg_init(&message);
        zmq_msg_recv(&message, socket, 0);

        if (s_interrupted) {
            printf("W: interrupt recived, killing server...\n");
            break;
        }
    }
    zmq_close(socket);
    zmq_ctx_destroy(context);
}
コード例 #5
0
 SubscriberZMQ::SubscriberZMQ(MessageProvider * messageProvider, const TString & subscribeId)
     : Subscriber(messageProvider, subscribeId)
     , m_context(0)
     , m_socket(0)
 {
     //init signal handler
     s_catch_signals();
 }
コード例 #6
0
ファイル: mdbroker.c プロジェクト: Neopallium/zguide
int main (int argc, char *argv [])
{
    int verbose = (argc > 1 && streq (argv [1], "-v"));

    s_version_assert (2, 1);
    s_catch_signals ();
    broker_t *self = s_broker_new (verbose);
    s_broker_bind (self, "tcp://*:5555");

    //  Get and process messages forever or until interrupted
    while (!s_interrupted) {
        zmq_pollitem_t items [] = { 
            { self->socket,  0, ZMQ_POLLIN, 0 } };
        zmq_poll (items, 1, HEARTBEAT_INTERVAL * 1000);

        //  Process next input message, if any
        if (items [0].revents & ZMQ_POLLIN) {
            zmsg_t *msg = zmsg_recv (self->socket);
            if (self->verbose) {
                s_console ("I: received message:");
                zmsg_dump (msg);
            }
            char *sender = zmsg_pop (msg);
            char *empty  = zmsg_pop (msg);
            char *header = zmsg_pop (msg);

            if (streq (header, MDPC_CLIENT))
                s_client_process (self, sender, msg);
            else
            if (streq (header, MDPW_WORKER))
                s_worker_process (self, sender, msg);
            else {
                s_console ("E: invalid message:");
                zmsg_dump (msg);
                zmsg_destroy (&msg);
            }
            free (sender);
            free (empty);
            free (header);
        }
        //  Disconnect and delete any expired workers
        //  Send heartbeats to idle workers if needed
        if (s_clock () > self->heartbeat_at) {
            s_broker_purge_workers (self);
            worker_t *worker = zlist_first (self->waiting);
            while (worker) {
                s_worker_send (self, worker, MDPW_HEARTBEAT, NULL, NULL);
                worker = zlist_next (self->waiting);
            }
            self->heartbeat_at = s_clock () + HEARTBEAT_INTERVAL;
        }
    }
    if (s_interrupted)
        printf ("W: interrupt received, shutting down...\n");

    s_broker_destroy (&self);
    return 0;
}
コード例 #7
0
ファイル: mdcliapi.hpp プロジェクト: AlexGiovanentti/zguide
   mdcli (std::string broker, int verbose)
   {
       assert (broker.size()!=0);
       s_version_assert (4, 0);

       m_broker = broker;
       m_context = new zmq::context_t(1);
       m_verbose = verbose;
       m_timeout = 2500;           //  msecs
       m_retries = 3;              //  Before we abandon
       m_client = 0;

       s_catch_signals ();
       connect_to_broker ();
   }
コード例 #8
0
ファイル: mdwrkapi.hpp プロジェクト: 343829084/zguide
    mdwrk (std::string broker, std::string service, int verbose)
    {
        s_version_assert (2, 1);

        m_broker = broker;
        m_service = service;
        m_context = new zmq::context_t (1);
        m_worker = 0;
        m_expect_reply = false;
        m_verbose = verbose;
        m_heartbeat = 2500;     //  msecs
        m_reconnect = 2500;     //  msecs

        s_catch_signals ();
        connect_to_broker ();
    }
コード例 #9
0
ファイル: mdcliapi2.c プロジェクト: Neopallium/zguide
mdcli_t *
mdcli_new (char *broker, int verbose)
{
    assert (broker);
    s_version_assert (2, 1);

    mdcli_t *self = (mdcli_t *) calloc (1, sizeof (mdcli_t));
    self->broker = strdup (broker);
    self->context = zmq_init (1);
    self->verbose = verbose;
    self->timeout = 2500;           //  msecs

    s_catch_signals ();
    s_mdcli_connect_to_broker (self);
    return self;
}
コード例 #10
0
ファイル: CameraManager2.cpp プロジェクト: chrolss/Quadvisio
CameraManager2::CameraManager2() {
    
    s_catch_signals ();
    
    vd = new vdIn;
    this->saving_buffer = false;
    this->grabbing = false;
    
    init_videoIn("/dev/video0", 640, 480, V4L2_PIX_FMT_MJPEG, 1);
    
    std::cout << vd->isstreaming << std::endl;
    
    std::thread t1(&CameraManager2::start_grabbing, this);
    t1.join();
    
    }
コード例 #11
0
ファイル: mdbroker.cpp プロジェクト: catinred2/zguide
int main (int argc, char *argv [])
{
    int verbose = (argc > 1 && strcmp (argv [1], "-v") == 0);

    s_version_assert (4, 0);
    s_catch_signals ();
    broker brk(verbose);
    brk.bind ("tcp://*:5555");

    brk.start_brokering();

    if (s_interrupted)
        printf ("W: interrupt received, shutting down...\n");

    return 0;
}
コード例 #12
0
ファイル: abd_reader.c プロジェクト: kishori82/COLAS
RawData  *ABD_read(
    char *obj_name,
    unsigned int op_num ,
    ClientArgs *client_args
) {
    s_catch_signals();

    int num_servers = count_num_servers(client_args->servers_str);
    void *sock_to_servers= get_socket_servers(client_args);
#ifdef DEBUG_MODE
    printf("\t\tObj name       : %s\n",obj_name);
    printf("\t\tWriter name    : %s\n",client_args->client_id);
    printf("\t\tOperation num  : %d\n",op_num);

    printf("\t\tServer string   : %s\n", client_args->servers_str);
    printf("\t\tPort to Use     : %s\n", client_args->port);
    printf("\t\tNum of Servers  : %d\n",num_servers);
#endif


    printf("READ %d\n", op_num);
    printf("\tMAX_TAG_VALUE (READER)\n");

    Tag max_tag;

    RawData *max_tag_value = malloc(sizeof(RawData));

    ABD_get_max_tag_value_phase(obj_name,  
                            op_num, 
                            sock_to_servers,       
                            num_servers, 
                            max_tag_value
                           );

    printf("\tWRITE_VALUE (READER)\n");
    ABD_write_value_phase(
                      obj_name, 
                      op_num, 
                      sock_to_servers, 
                      num_servers, 
                      max_tag_value,
                      max_tag
                    );

   return max_tag_value;
}
コード例 #13
0
ファイル: clone.c プロジェクト: Neopallium/zguide
clone_t *
clone_new (void)
{
    clone_t
        *self;

    s_catch_signals ();
    self = (clone_t *) malloc (sizeof (clone_t));
    self->context = zmq_init (1);
    self->control = zmq_socket (self->context, ZMQ_PAIR);
    int rc = zmq_bind (self->control, "inproc://clone");
    assert (rc == 0);

    pthread_t thread;
    pthread_create (&thread, NULL, clone_agent, self->context);
    pthread_detach (thread);

    return self;
}
コード例 #14
0
ファイル: abd_reader.c プロジェクト: kishori82/COLAS
int main (void) {
    int i ;

    char *payload = (char *)malloc(100000000*sizeof(char));
    unsigned int size = 100000000*sizeof(char);

    /*
       char *servers[]= {
                         "172.17.0.7", "172.17.0.5",
                         "172.17.0.4", "172.17.0.6",
                         "172.17.0.3"
                       };

    */

    /*
       char *servers[] = {
    "172.17.0.22", "172.17.0.21", "172.17.0.18", "172.17.0.17", "172.17.0.20", "172.17.0.16", "172.17.0.19", "172.17.0.15", "172.17.0.14", "172.17.0.13", "172.17.0.12", "172.17.0.11", "172.17.0.10", "172.17.0.9", "172.17.0.7", "172.17.0.8", "172.17.0.6", "172.17.0.5", "172.17.0.4", "172.17.0.3"
                         };
    */

    char *servers[]= {
        "172.17.0.2"
    };


    unsigned int num_servers = 1;
    char port[]= {PORT};

    char writer_id[] = { "writer_1"};
    char obj_name[] = {OBJECT};

    unsigned int op_num;
    s_catch_signals();

    for( i=0; i < 5; i++) {
        printf("\nWRITE %d\n", i);
        //ABD_write(obj_name, writer_id, i,  payload, size, servers, port);
    }

//   zclock_sleep(50*1000);
    return 0;
}
コード例 #15
0
ファイル: flcliapi.c プロジェクト: tzuryby/zguide
flcliapi_t *
flcliapi_new (void)
{
    flcliapi_t
        *self;

    s_catch_signals ();
    self = (flcliapi_t *) malloc (sizeof (flcliapi_t));
    self->context = zmq_init (1);
    self->control = zmq_socket (self->context, ZMQ_PAIR);

    int rc = zmq_bind (self->control, "inproc://flcliapi");
    assert (rc == 0);

    pthread_t thread;
    pthread_create (&thread, NULL, flcliapi_task, self->context);
    pthread_detach (thread);

    return self;
}
コード例 #16
0
ファイル: mycached.cpp プロジェクト: david-pp/tinyworld
bool MyCacheServer::init()
{
	s_catch_signals();

	try 
	{
		context_ = new zmq::context_t(1);

		clients_socket_ = new zmq::socket_t(*context_, ZMQ_ROUTER);
		if (clients_socket_)
		{
			clients_socket_->bind(address_.c_str());
			LOG4CXX_INFO(logger, "init - bind client sockets sucess:" << address_);
		}

		workers_socket_ = new zmq::socket_t(*context_, ZMQ_ROUTER);
		if (workers_socket_)
		{
			workers_socket_->bind("inproc://workers");
			LOG4CXX_INFO(logger, "init - bind worker sockets sucess:inproc://workers");
		}
	}
	catch (std::exception& err)
	{
		LOG4CXX_ERROR(logger, "init - bind failed :" << err.what());
		return false;
	}

    //  Launch pool of worker threads
    for (int i = 0; i < workernum_; i++) 
    {
    	MyCacheWorker* worker = new MyCacheWorker(this->context_, "inproc://workers", i);
    	if (worker && worker->init())
    	{
    		worker_thrds.create_thread(boost::bind(&MyCacheWorker::run, worker));
    	}
    }

	return true;
}
コード例 #17
0
ファイル: interrupt.c プロジェクト: 343829084/zguide
int main (void)
{
    void *context = zmq_ctx_new ();
    void *socket = zmq_socket (context, ZMQ_REP);
    zmq_bind (socket, "tcp://*:5555");

    s_catch_signals ();
    while (true) {
        //  Blocking read will exit on a signal
        zmq_msg_t message;
        zmq_msg_init (&message);
        zmq_msg_recv (&message, socket, 0);

        if (s_interrupted) {
            printf ("W: interrupt received, killing server...\n");
            break;
        }
    }
    zmq_close (socket);
    zmq_ctx_destroy (context);
    return 0;
}
コード例 #18
0
ファイル: hwserver.c プロジェクト: kmiku7/practice
int main(void){

	void *context = zmq_ctx_new();
	void *responder = zmq_socket(context, ZMQ_REP);
	int rc = zmq_bind(responder, "tcp://*:5555");
	assert( rc==0);

  s_catch_signals();

	while(1){
		char buffer[10];
		int ret = zmq_recv(responder, buffer, 10, 0);
    if(zmq_errno()==EINTR)
    {
      fprintf(stderr, "BREAK!\n");
      break;
    }
		printf("Reveiver Hello\n");
		sleep(1);
		zmq_send(responder, "World", 5, 0);
	}
	return 0;
}
コード例 #19
0
ファイル: flib_cfg.cpp プロジェクト: Jiray/flesnet
int main(int argc, char* argv[]) {
  s_catch_signals();
  int ret = 0;

  try {

    parameters par(argc, argv);

    std::unique_ptr<flib::flib_device_flesin> flib;
    // create FLIB
    if (par.flib_autodetect()) {
      flib = std::unique_ptr<flib::flib_device_flesin>(
          new flib::flib_device_flesin(0));
    } else {
      flib = std::unique_ptr<flib::flib_device_flesin>(
          new flib::flib_device_flesin(par.flib_addr().bus, par.flib_addr().dev,
                                       par.flib_addr().func));
    }
    std::vector<flib::flib_link_flesin*> links = flib->links();
    std::vector<std::unique_ptr<flib::flim>> flims;

    L_(info) << "Configuring FLIB: " << flib->print_devinfo();

    // FLIB global configuration
    // set even if unused
    flib->id_led(par.identify());
    flib->set_mc_time(par.mc_size());

    L_(debug) << "Tatal FLIB links: " << flib->number_of_links();

    // FLIB per link configuration
    for (size_t i = 0; i < flib->number_of_links(); ++i) {
      L_(debug) << "Initializing link " << i;

      if (par.link(i).source == disable) {
        links.at(i)->set_data_sel(flib::flib_link::rx_disable);
      } else if (par.link(i).source == pgen_near) {
        links.at(i)->set_data_sel(flib::flib_link::rx_pgen);
        // create internal FLIM
        try {
          flims.push_back(
              std::unique_ptr<flib::flim>(new flib::flim(links.at(i))));
        } catch (const std::exception& e) {
          L_(error) << e.what();
          exit(EXIT_FAILURE);
        }
        flims.back()->reset_datapath();
        if (!flims.back()->get_pgen_present()) {
          L_(error) << "FLIM build does not support pgen";
          exit(EXIT_FAILURE);
        }
        flims.back()->set_pgen_mc_size(par.mc_size());
        flims.back()->set_pgen_rate(par.pgen_rate());
        flims.back()->set_pgen_ids(par.link(i).eq_id);
        flims.back()->set_data_source(flib::flim::pgen);
      } else if (par.link(i).source == flim || par.link(i).source == pgen_far) {
        links.at(i)->set_data_sel(flib::flib_link::rx_link);
        // create FLIM
        try {
          flims.push_back(
              std::unique_ptr<flib::flim>(new flib::flim(links.at(i))));
        } catch (const std::exception& e) {
          L_(error) << e.what();
          exit(EXIT_FAILURE);
        }
        flims.back()->reset_datapath();
        if (par.link(i).source == flim) {
          flims.back()->set_data_source(flib::flim::user);
        } else { // pgen_far
          if (!flims.back()->get_pgen_present()) {
            L_(error) << "FLIM build does not support pgen";
            exit(EXIT_FAILURE);
          }
          flims.back()->set_pgen_mc_size(par.mc_size());
          flims.back()->set_pgen_rate(par.pgen_rate());
          flims.back()->set_pgen_ids(par.link(i).eq_id);
          flims.back()->set_data_source(flib::flim::pgen);
        }
      }
    }

    L_(debug) << "Exiting";

  } catch (std::exception const& e) {
    L_(fatal) << "exception: " << e.what();
  }

  return ret;
}
コード例 #20
0
ファイル: casgc_client.c プロジェクト: kishori82/COLAS
char *CASGC_read(
    char *obj_name,
    char *writer_id,
    unsigned int op_num ,
//                char *payload,
    char *servers_str,
    char *port
) {
    s_catch_signals();
    int j;
    printf("Obj name       : %s\n",obj_name);
    printf("Writer name    : %s\n",writer_id);
    printf("Operation num  : %d\n",op_num);

    /* char *myb64 = (char *)malloc(strlen(payload));
     b64_decode(payload, myb64);
     printf("Encoded string  : %s\n", payload);
     free(myb64);
    */
    printf("Server string   : %s\n", servers_str);
    printf("Port to Use     : %s\n", port);

    int num_servers = count_num_servers(servers_str);

    printf("Num of Servers  : %d\n",num_servers);

//    printf("Decoded string  : %s\n", myb64);
    char **servers = create_server_names(servers_str);
    for(j=0; j < num_servers; j++) {
        printf("\tServer : %s\n", servers[j]);
    }
    printf("\n");

    zctx_t *ctx  = zctx_new();
    void *sock_to_servers = zsocket_new(ctx, ZMQ_DEALER);
    zctx_set_linger(ctx, 0);
    assert (sock_to_servers);

    zsocket_set_identity(sock_to_servers,  writer_id);
    for(j=0; j < num_servers; j++) {
        char *destination = create_destination(servers[j], port);
        int rc = zsocket_connect(sock_to_servers, destination);
        assert(rc==0);
        free(destination);
    }

    printf("READ %d\n", op_num);
    printf("     MAX_TAG_VALUE (READER)\n");

    char *payload;
    TAG max_tag;
    get_max_tag_value_phase(obj_name,  op_num, sock_to_servers, servers, num_servers, port, &max_tag, &payload);

    printf("\tmax tag (%d,%s)\n\n", max_tag.z, max_tag.id);

    printf("     WRITE_VALUE (READER)\n");
    int size = strlen(payload);
    write_value_phase(obj_name, writer_id,  op_num, sock_to_servers, servers,
                      num_servers, port, payload, size, max_tag);

    zsocket_destroy(ctx, sock_to_servers);
    zctx_destroy(&ctx);


    return payload;
}
コード例 #21
0
ファイル: casgc_client.c プロジェクト: kishori82/COLAS
// ABD write
bool CASGC_write(
    char *obj_name,
    char *writer_id,
    unsigned int op_num ,
    char *payload,
    unsigned int size,
    char *servers_str,
    char *port

) {
    s_catch_signals();
    int j;
    printf("Obj name       : %s\n",obj_name);
    printf("Writer name    : %s\n",writer_id);
    printf("Operation num  : %d\n",op_num);
    printf("Size           : %d\n", size);
    printf("Size of        : %u\n", (unsigned int)strlen(payload));

    char *myb64 = (char *)malloc(strlen(payload));

    b64_decode(payload, myb64);

    printf("Encoded string  : %s\n", payload);
    printf("Server string   : %s\n", servers_str);
    printf("Port to Use     : %s\n", port);

    int num_servers = count_num_servers(servers_str);

    printf("Num of Servers  : %d\n",num_servers);

//    printf("Decoded string  : %s\n", myb64);
    char **servers = create_server_names(servers_str);
    for(j=0; j < num_servers; j++) {
        printf("\tServer : %s\n", servers[j]);
    }
    printf("\n");
    free(myb64);

    zctx_t *ctx  = zctx_new();
    void *sock_to_servers = zsocket_new(ctx, ZMQ_DEALER);
    zctx_set_linger(ctx, 0);
    assert (sock_to_servers);

    zsocket_set_identity(sock_to_servers,  writer_id);
    for(j=0; j < num_servers; j++) {
        char *destination = create_destination(servers[j], port);
        int rc = zsocket_connect(sock_to_servers, (const char *)destination);
        assert(rc==0);
        free(destination);
    }

    printf("WRITE %d\n", op_num);
    printf("     MAX_TAG (WRITER)\n");

    TAG max_tag=  get_max_tag_phase(obj_name,  op_num, sock_to_servers, servers, num_servers, port);

    //Create a new tag
    TAG new_tag;
    new_tag.z = max_tag.z + 1;
    strcpy(new_tag.id, writer_id);


    printf("     WRITE_VALUE (WRITER)\n");
    write_value_phase(obj_name, writer_id,  op_num, sock_to_servers, servers,
                      num_servers, port, payload, size, max_tag);

    zsocket_destroy(ctx, sock_to_servers);
    zctx_destroy(&ctx);


    return true;
}
コード例 #22
0
int main(int argc, char **argv) {
	int rc;

	setup_config(argc, argv);

	if (config.pull == NULL) {
		usage(argv[0]);
		errx(EXIT_FAILURE, "no pull option set");
	}

	if (config.pub == NULL) {
		usage(argv[0]);
		errx(EXIT_FAILURE, "no pub option set");
	}

	void *context = zmq_init(1);
	assert(context);

	void *pull_socket = zmq_socket(context, ZMQ_PULL);
	assert(pull_socket);

	void *pub_socket = zmq_socket(context, ZMQ_PUB);
	assert(pub_socket);

	if (config.hwm > 0) {
		rc = zmq_setsockopt(pub_socket, ZMQ_HWM, &config.hwm, sizeof(config.hwm));
		if (rc != 0)
			errx(EXIT_FAILURE, "failed to set high-water mark \"%"PRIu64"\"", config.hwm);
	}

	if (config.swap > 0) {
		if (config.hwm < 1)
			errx(EXIT_FAILURE, "hwm must be set to use swap");

		rc = zmq_setsockopt(pub_socket, ZMQ_SWAP, &config.swap, sizeof(config.swap));

		if (rc != 0)
			errx(EXIT_FAILURE, "failed to set swap size \"%"PRIu64"\"", config.swap);
	}

	rc = zmq_bind(pull_socket, config.pull);
	if (rc != 0)
		errx(EXIT_FAILURE, "failed to bind pull endpoint \"%s\"", config.pull);

	rc = zmq_bind(pub_socket, config.pub);
	if (rc != 0)
		errx(EXIT_FAILURE, "failed to bind pub endpoint \"%s\"", config.pub);

	s_catch_signals();

	int64_t more;
	size_t more_size;

	zmq_msg_t msg;
	zmq_msg_init(&msg);

	while (!s_interrupted) {
		if (zmq_recv(pull_socket, &msg, 0)) continue;

		more_size = sizeof(more);
		zmq_getsockopt(pull_socket, ZMQ_RCVMORE, &more, &more_size);
		zmq_send(pub_socket, &msg, more ? ZMQ_SNDMORE : 0);
	}

	zmq_close(pull_socket);
	zmq_close(pub_socket);
	zmq_term(context);

	printf("\n");

	return EXIT_SUCCESS;
}
コード例 #23
0
ファイル: interrupt.c プロジェクト: Andy-hpliu/zguide
int main (void)
{
    int rc;

    void *context = zmq_ctx_new ();
    void *socket = zmq_socket (context, ZMQ_REP);
    zmq_bind (socket, "tcp://*:5555");

    int pipefds[2];
    rc = pipe(pipefds);
    if (rc != 0) {
        perror("Creating self-pipe");
        exit(1);
    }
    for (int i = 0; i < 2; i++) {
        int flags = fcntl(pipefds[0], F_GETFL, 0);
        if (flags < 0) {
            perror ("fcntl(F_GETFL)");
            exit(1);
        }
        rc = fcntl (pipefds[0], F_SETFL, flags | O_NONBLOCK);
        if (rc != 0) {
            perror ("fcntl(F_SETFL)");
            exit(1);
        }
    }

    s_catch_signals (pipefds[1]);

    zmq_pollitem_t items [] = {
        { 0, pipefds[0], ZMQ_POLLIN, 0 },
        { socket, 0, ZMQ_POLLIN, 0 }
    };

    while (1) {
        rc = zmq_poll (items, 2, -1);
        if (rc == 0) {
            continue;
        } else if (rc < 0) {
            if (errno == EINTR) { continue; }
            perror("zmq_poll");
            exit(1);
        }

        // Signal pipe FD
        if (items [0].revents & ZMQ_POLLIN) {
            char buffer [1];
            read (pipefds[0], buffer, 1);  // clear notifying byte
            printf ("W: interrupt received, killing server...\n");
            break;
        }

        // Read socket
        if (items [1].revents & ZMQ_POLLIN) {
            char buffer [255];
            // Use non-blocking so we can continue to check self-pipe via zmq_poll
            rc = zmq_recv (socket, buffer, 255, ZMQ_NOBLOCK);
            if (rc < 0) {
                if (errno == EAGAIN) { continue; }
                if (errno == EINTR) { continue; }
                perror("recv");
                exit(1);
            }
            printf ("W: recv\n");

            // Now send message back.
            // ...
        }
    }

    printf ("W: cleaning up\n");
    zmq_close (socket);
    zmq_ctx_destroy (context);
    return 0;
}
コード例 #24
0
ファイル: znowflaked.c プロジェクト: brandonmenc/znowflake
//  Main
int
main (int argc, char **argv)
{
        //  Do some initial sanity checking
        assert (TIME_BITLEN + MACHINE_BITLEN + SEQ_BITLEN == 64);

        //  Parse command-line arguments
        int opt;
        int has_port_opt = 0;
        int has_machine_opt = 0;
        int has_config_file_opt = 0;
        int has_daemonize_opt = 0;
        int machine_specified = 0;

        const char *config_file_path;
        int port = DEFAULT_PORT;
        uint64_t machine;
        
        while ((opt = getopt (argc, argv, "hp:m:f:d")) != -1) {
                switch (opt) {
                case 'h':
                        print_help ();
                        exit (EXIT_SUCCESS);
                case 'p':
                        has_port_opt = 1;
                        port = atoi (optarg);
                        break;
                case 'm':
                        has_machine_opt = 1;
                        machine = atoll (optarg);
                        machine_specified = 1;
                        break;
                case 'f':
                        has_config_file_opt = 1;
                        config_file_path = optarg;
                        break;
                case 'd':
                        has_daemonize_opt = 1;
                        break;
                }
        }

        //  Read the config file
        if (has_config_file_opt) {
                config_t cfg;

                config_init (&cfg);

                if (!config_read_file (&cfg, config_file_path)) {
                        config_destroy (&cfg);
                        fprintf (stderr, "Invalid config file\n");
                        exit (EXIT_FAILURE);
                }

                long unsigned int machine_from_file;
                if (config_lookup_int (&cfg, "machine", &machine_from_file) && !has_machine_opt) {
                        machine_specified = 1;
                        machine = (uint64_t) machine_from_file;
                }

                long unsigned int port_from_file;
                if (config_lookup_int (&cfg, "port", &port_from_file) && !has_port_opt)
                        port = (int) port_from_file;

                
        }

        //  Sanity check the machine number
        if (!machine_specified) {
                fprintf (stderr, "No machine number specified.\n");
                exit (EXIT_FAILURE);
        }
        else if (machine > MACHINE_MAX) {
                fprintf (stderr, "Machine number too large. Cannot be greater than %llu\n", MACHINE_MAX);
                exit (EXIT_FAILURE);
        }

        //  Daemonize
        static char *pid_file_path = "/var/run/znowflaked.pid";
        int pid_file;
        
        if (has_daemonize_opt) {
                pid_t pid, sid;

                pid = fork ();
                if (pid < 0) {
                        exit (EXIT_FAILURE);
                }
                if (pid > 0) {
                        exit (EXIT_SUCCESS);
                }

                umask (0);
                
                sid = setsid ();
                if (sid < 0) {
                        exit (EXIT_FAILURE);
                }
        
                if ((chdir ("/")) < 0) {
                        exit (EXIT_FAILURE);
                }

                //  Create and lock the pid file
                pid_file = open (pid_file_path, O_CREAT | O_RDWR, 0666);
                if (pid_file > 0) {
                        int rc = lockf (pid_file, F_TLOCK, 0);
                        if (rc) {
                                switch (errno) {
                                case EACCES:
                                case EAGAIN:
                                        fprintf (stderr, "PID file already locked\n");
                                        break;
                                case EBADF:
                                        fprintf (stderr, "Bad pid file\n");
                                        break;
                                default:
                                        fprintf (stderr, "Could not lock pid file\n");
                                }
                                exit (EXIT_FAILURE);
                        }

                        char *pid_string = NULL;
                        int pid_string_len = asprintf (&pid_string, "%ld", (long) getpid ());
                        write (pid_file, pid_string, pid_string_len);
                }
        
                close (STDIN_FILENO);
                close (STDOUT_FILENO);
                close (STDERR_FILENO);
        }

        //  Sleep for 1ms to prevent collisions
        struct timespec ms;
        ms.tv_sec = 0;
        ms.tv_nsec = 1000000;
        nanosleep (&ms, NULL);

        //  Initialize ZeroMQ
        zctx_t *context = zctx_new ();
        assert (context);
        void *socket = zsocket_new (context, ZMQ_REP);
        assert (socket);
        assert (streq (zsocket_type_str (socket), "REP"));
        int rc = zsocket_bind (socket, "tcp://*:%d", port);
        if (rc != port) {
                printf ("E: bind failed: %s\n", strerror (errno));
                exit (EXIT_FAILURE);
        }

        //  Start remembering the last timer tick
        uint64_t ts = 0;
        uint64_t last_ts = 0;
        uint64_t seq = 0;

        //  Main loop
        s_catch_signals ();        
        while (1) {
                //  Wait for the next request
                zmsg_t *request_msg = zmsg_new ();
                assert (request_msg);
                request_msg = zmsg_recv (socket);
                assert (request_msg);
                zmsg_destroy (&request_msg);

                //  Grab a time click
                last_ts = ts;
                ts = get_ts ();

                //  Make sure the system clock wasn't reversed on us
                if (ts < last_ts) {
                        //  Wait until it catches up
                        while (ts <= last_ts) {
                                nanosleep (&ms, NULL);
                                ts = get_ts ();
                        }
                }

                //  Increment the sequence number
                if (ts != last_ts) {
                        //  We're in a new time click, so reset the sequence
                        seq = 0;
                }
                else if (seq == SEQ_MAX) {
                        //  Wrapped sequence, so wait for the next time tick
                        seq = 0;
                        nanosleep (&ms, NULL);
                }
                else {
                        //  Still in the same time click
                        seq++;
                }

                //  Build the ID and put it in network byte order
                uint64_t id = build_id (ts, machine, seq);
                uint64_t id_be64 = htobe64 (id);

                //  Reply
                zmsg_t *reply_msg = zmsg_new ();
                assert (reply_msg);
                zframe_t *frame = zframe_new (&id_be64, 8);
                assert (frame);
                zmsg_push (reply_msg, frame);
                assert (zmsg_size (reply_msg) == 1);
                assert (zmsg_content_size (reply_msg) == 8);
                zmsg_send (&reply_msg, socket);
                assert (reply_msg == NULL);

                //  Exit program
                if (s_interrupted) {
                        printf ("interrupt received, killing server…\n");
                        break;
                }
        }
        zctx_destroy (&context);
        if (has_daemonize_opt) {
                if (pid_file > 0) {
                        unlink (pid_file_path);
                        close (pid_file);
                }
        }
        exit (EXIT_SUCCESS);
}
コード例 #25
0
ファイル: main.cpp プロジェクト: alex-dot/syncbox
int main_application(int argc, char* argv[])
{
  // opening zeromq context
  zmqpp::context z_context;

  if (sodium_init() == -1) {
    std::cerr << "[E] Could not initialize crypto library libsodium."
              << std::endl;
    return 1;
  }

  // we eagerly initialize all singletons here
  Boxoffice::getInstance();
  int return_val = Config::initialize(argc, argv);
  if (return_val != 0) {
    return return_val;
  }

  if (sodium_init() == -1) {
    std::cerr << "[E] Could not initialize crypto library libsodium."
              << std::endl;
    return 1;
  }

  // catch signals
  s_catch_signals();

  // bind process broadcast pub
  zmqpp::socket z_broadcast(z_context, zmqpp::socket_type::pub);
  z_broadcast.bind("inproc://f_broadcast");
  // bind to boxoffice endpoint
  zmqpp::socket z_boxoffice(z_context, zmqpp::socket_type::pair);
  z_boxoffice.bind("inproc://f_bo_main_pair");

  // opening boxoffice thread
  if (F_MSG_DEBUG) printf("main: opening boxoffice thread\n");
  boost::thread bo_thread(boxoffice_thread, &z_context);

  // wait for signal from boxoffice
  if (F_MSG_DEBUG) printf("main: waiting for boxoffice to send exit signal\n");
  while(s_interrupted == 0)
  {
    usleep(100);
  }

  std::cout << "main: received interrupt, broadcasting signal to boxoffice..." << std::endl;
  std::stringstream* message = new std::stringstream();
  *message << F_SIGTYPE_LIFE << " " << F_SIGLIFE_INTERRUPT;
  zmqpp::message* z_msg = new zmqpp::message();
  *z_msg << message->str();
  z_boxoffice.send(*z_msg);
  delete z_msg;

  std::cout << "main: boxoffice exited, broadcasting signal..." << std::endl;
  message = new std::stringstream();
  *message << F_SIGTYPE_LIFE << " " << F_SIGLIFE_INTERRUPT;
  z_msg = new zmqpp::message();
  *z_msg << message->str();
  z_broadcast.send(*z_msg);

  std::cout << "main: waiting for boxoffice to send exit..." << std::endl;
  z_msg = new zmqpp::message();
  z_boxoffice.receive(*z_msg);
  std::stringstream sstream;
  sstream << z_msg->get(0);
  int msg_type, msg_signal;
  sstream >> msg_type >> msg_signal;
  delete z_msg;

  sstream >> msg_type >> msg_signal;
  if ( msg_type != F_SIGTYPE_LIFE && msg_signal != F_SIGLIFE_EXIT ) return 1;
  if (F_MSG_DEBUG) printf("main: boxoffice sent exit signal, cleaning up and exiting...\n");

  bo_thread.join();

  z_boxoffice.close();
  z_broadcast.close();

  z_context.terminate();

  return 0;
}
コード例 #26
0
ファイル: clonecli3.c プロジェクト: Neopallium/zguide
int main (void) 
{
    //  Prepare our context and subscriber
    void *context = zmq_init (1);
    void *subscriber = zmq_socket (context, ZMQ_SUB);
    zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, "", 0);
    zmq_connect (subscriber, "tcp://localhost:5556");

    void *snapshot = zmq_socket (context, ZMQ_XREQ);
    zmq_connect (snapshot, "tcp://localhost:5557");

    void *updates = zmq_socket (context, ZMQ_PUSH);
    zmq_connect (updates, "tcp://localhost:5558");

    s_catch_signals ();
    zhash_t *kvmap = zhash_new ();
    srandom ((unsigned) time (NULL));
    
    //  Get state snapshot
    int64_t sequence = 0;
    s_send (snapshot, "I can haz state?");
    while (!s_interrupted) {
        kvmsg_t *kvmsg = kvmsg_recv (snapshot);
        if (!kvmsg)
            break;          //  Interrupted
        if (streq (kvmsg_key (kvmsg), "KTHXBAI")) {
            sequence = kvmsg_sequence (kvmsg);
            kvmsg_destroy (&kvmsg);
            break;          //  Done
        }
        kvmsg_store (&kvmsg, kvmap);
    }
    printf ("I: received snapshot=%" PRId64 "\n", sequence);
    int zero = 0;
    zmq_setsockopt (snapshot, ZMQ_LINGER, &zero, sizeof (zero));
    zmq_close (snapshot);

    int64_t alarm = s_clock () + 1000;
    while (!s_interrupted) {
        zmq_pollitem_t items [] = { { subscriber, 0, ZMQ_POLLIN, 0 } };
        int tickless = (int) ((alarm - s_clock ()));
        if (tickless < 0)
            tickless = 0;
        int rc = zmq_poll (items, 1, tickless * 1000);
        if (rc == -1)
            break;              //  Context has been shut down
        
        if (items [0].revents & ZMQ_POLLIN) {
            kvmsg_t *kvmsg = kvmsg_recv (subscriber);
            if (!kvmsg)
                break;          //  Interrupted

            //  Discard out-of-sequence kvmsgs, incl. heartbeats
            if (kvmsg_sequence (kvmsg) > sequence) {
                sequence = kvmsg_sequence (kvmsg);
                kvmsg_store (&kvmsg, kvmap);
                printf ("I: received update=%" PRId64 "\n", sequence);
            }
            else
                kvmsg_destroy (&kvmsg);
        }
        //  If we timed-out, generate a random kvmsg
        if (s_clock () >= alarm) {
            kvmsg_t *kvmsg = kvmsg_new (0);
            kvmsg_fmt_key  (kvmsg, "%d", randof (10000));
            kvmsg_fmt_body (kvmsg, "%d", randof (1000000));
            kvmsg_send (kvmsg, updates);
            kvmsg_destroy (&kvmsg);
            alarm = s_clock () + 1000;
        }
    }
    zhash_destroy (&kvmap);

    printf (" Interrupted\n%" PRId64 " messages in\n", sequence);
    zmq_setsockopt (updates, ZMQ_LINGER, &zero, sizeof (zero));
    zmq_close (updates);
    zmq_close (subscriber);
    zmq_term (context);
    return 0;
}
コード例 #27
0
ファイル: xstorage.cpp プロジェクト: ATNoG/remoteLevelDB
int main(int argc, char** argv)
{
    s_catch_signals();
    std::string configPath(CONFIG);

    if(argc > 1)
    {
        configPath = std::string(argv[1]);
    }

    std::ifstream file;
    std::stringstream ss;

    file.open(configPath.c_str());
    if (file.is_open())
    {
        ss << file.rdbuf();   
        file.close();
    }
    else
    {
        exit(1);
    }

    json::JSONObject config(ss);

    leveldb::Options options;
    options.create_if_missing = true;
    leveldb::DB::Open(options, config.get("StorageDirectory"), &db);

    context = zmq_init(1);
    void *frontend = zmq_socket(context, ZMQ_ROUTER),
         *backend  = zmq_socket(context, ZMQ_DEALER);
    zmq_bind(frontend, config.get("StorageAdd").c_str());
    zmq_bind(backend, "inproc://storageWorkers");

    MessageFactory *msgFactory = new MessageFactory();
    ActionFactory *actionsFactory = new ActionFactory(db);

    nExecutors = config.getInt("StorageNWorkers");
    executors = new Executor*[nExecutors];

    for(size_t i = 0; i < nExecutors; i++)
    {
        executors[i] = new Executor(msgFactory, actionsFactory, context);
        executors[i]->start();
    }    
    zmq_device(ZMQ_QUEUE, frontend, backend);

    for(size_t i = 0; i < nExecutors; i++)
    {
        delete executors[i];
    }

    delete actionsFactory;
    delete msgFactory;
    delete executors;
    zmq_close(frontend);
    zmq_close(backend);
    zmq_term(context);
    return 0;
}
コード例 #28
0
ファイル: framegrabber.c プロジェクト: jbolling/LaserGimbal
int main(int argc, char **argv) {
	s_catch_signals ();
	for (;;) {
		int idx;
		int c;

		c = getopt_long(argc, argv,
			short_options, long_options, &idx);

		if (-1 == c)
			break;

		switch (c) {
		case 0: /* getopt_long() flag */
			break;

		case 'd':
			dev_name = optarg;
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);

		case 'm':
			io = IO_METHOD_MMAP;
			break;

		case 'r':
			io = IO_METHOD_READ;
			break;

		case 'u':
			io = IO_METHOD_USERPTR;
			break;

		case 'W':
			// set width
			width = atoi(optarg);
			set_format++;
			break;

		case 'H':
			// set height
			height = atoi(optarg);
			set_format++;
			break;

		case 'I':
			// set fps
			fps = atoi(optarg);
			break;

		case 'f':
			// set pixel format
			if (strcmp(optarg, "YUYV") == 0 || strcmp(optarg, "yuyv") == 0) {
				pixel_format = V4L2_PIX_FMT_YUYV;
				set_format++;
			} else if (strcmp(optarg, "MJPG") == 0 || strcmp(optarg, "mjpg") == 0) {
				pixel_format = V4L2_PIX_FMT_MJPEG;
				set_format++;
			} else if (strcmp(optarg, "H264") == 0 || strcmp(optarg, "h264") == 0) {
				pixel_format = V4L2_PIX_FMT_H264;
				set_format++;
			}
			break;

		case 't':
			// set timeout
			timeout = atoi(optarg);
			break;

		case 'T':
			// set max timeout
			timeouts_max = atoi(optarg);
			break;

		case 'o':
			out_buf++;
			break;

		case 'c':
			errno = 0;
			frame_count = strtol(optarg, NULL, 0);
			if (errno)
				errno_exit(optarg);
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}
        clock_t begin, end;
        double time_spent;
        
        begin = clock();
	open_device();
	init_device();
	start_capturing();
        end = clock();
        time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
        fprintf(stderr, "Startup took %f seconds\n", time_spent);

	mainloop();

        begin = clock();
	stop_capturing();
	uninit_device();
	close_device();
        end = clock();
        time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
        fprintf(stderr, "Shutdown took %f seconds\n", time_spent);
	fprintf(stderr, "\n");
	return 0;
}