std::vector<dmod::array1d> getLearningSignals( int signalsAmount, 
											   dmod::Tomogram &tomo, 
											   std::default_random_engine &gen, 
											   cv::Mat &mask )
{
	std::vector<dmod::array1d> signals(signalsAmount);
	size_t h = tomo.getHeight();
	size_t w = tomo.getWidth();

	for (auto iter = signals.begin(); iter != signals.end(); ++iter)
	{
		size_t y = gen() % h;
		size_t x = gen() % w;
		if (mask.ptr()[y * w + x] > 0)
		{
			*iter = tomo.getSignal1D(x, y, 0, dmod::Axis::Z);
		}
		else
		{
			iter--;
		}
	}

	return std::move(signals);
}
Exemple #2
0
static void init_everything(void) {
	log_init("rtpengine");
	log_format(rtpe_config.log_format);
	recording_fs_init(rtpe_config.spooldir, rtpe_config.rec_method, rtpe_config.rec_format);
	rtpe_ssl_init();

#if !GLIB_CHECK_VERSION(2,32,0)
	g_thread_init(NULL);
#endif

#if !(GLIB_CHECK_VERSION(2,36,0))
	g_type_init();
#endif

	signals();
	resources();
	sdp_init();
	dtls_init();
	ice_init();
	crypto_init_main();
	interfaces_init(&rtpe_config.interfaces);
	iptables_init();
	control_ng_init();
	if (call_interfaces_init())
		abort();
	statistics_init();
	codeclib_init(0);
	media_player_init();
}
/////////////////////
///getLearningData///
/////////////////////
std::vector<dmod::array1d> getLearningSignals( int signalsAmount, 
											   dmod::array1d &background, 
											   dmod::array1d &frequency, 
											   float E_min, 
											   float E_max, 
											   float sigma, 
											   float delta_z, 
											   std::default_random_engine &gen )
{
	size_t N = background.size();
	if (frequency.size() != N)
	{
		std::cout << "Error. Arrays sizes are mismatched." << std::endl;
		return std::vector<dmod::array1d>(0);
	}
	std::vector<dmod::array1d> signals(signalsAmount);
	for (int k = 0; k < signalsAmount; k++)
	{
		float startPhase = (float)(gen() % 100000000) / 100000000 * 2 * M_PI;
		dmod::array1d phase = dmod::phaseFromFrequency(frequency, startPhase, delta_z);
		dmod::array1d noise = dmod::createNormalNoise(0, 10, N, gen);
		dmod::array1d amplitude = dmod::randomGaussianAmplitude(static_cast<float>(N), E_min, E_max, sigma, 6, gen);

		signals[k] = dmod::createSignal1D(background, amplitude, phase, noise);
	}
	return std::move(signals);
}
Exemple #4
0
test_result test(test_parameters p) {
    unsigned call_count = 0;

    auto start = now();

    // make signals
    //
    using signal_type = boost::signals2::signal<void()>;
    std::vector<signal_type> signals(p.subjects_count);

    // observe all signals
    std::vector<boost::signals2::scoped_connection> connections;
    for (auto& signal : signals) {
        for (std::size_t i = 0; i < p.observers_count; i++) {
            connections.emplace_back(signal.connect([&]() { call_count++; }));
        }
    }

    auto builded = now();

    // call signals
    for (auto& signal : signals) {
        signal();
    }
    auto called = now();

    // destroy connections and signals
    connections.clear();
    signals.clear();
    auto end = now();

    assert(call_count == p.subjects_count * p.observers_count);

    return {(builded - start), (called - builded), (end - called)};
}
Exemple #5
0
int main()
{
    /* Create instances of needed components */
    auto msg_center =
        std::make_shared<messaging::message_center>();


    /* Start socket listeners managed by server_manager */
    auto sess_iface =
        std::static_pointer_cast<messaging::session_interface>(msg_center);
    auto serv_mgr = std::make_unique<network::server_manager>(sess_iface);
    serv_mgr->start_serving();


    /* Block thread until interrupted by a signal, then clean up and exit */
    boost::asio::io_service io_service;
    boost::asio::signal_set signals(io_service);
    signals.add(SIGINT);
    signals.add(SIGTERM);
    signals.async_wait(signal_handler);

    io_service.run();

    serv_mgr->stop_serving();
}
int main() {
  try {
    request_handler handler;
    auto io_service = std::make_shared<boost::asio::io_service>();
    echo_server server(
        echo_server::options(handler).io_service(io_service).port("8000"));

    // Clean shutdown when pressing Ctrl+C.
    boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);
    signals.async_wait([&server](const boost::system::error_code& ec,
                                 int /* signal_number */) {
      if (!ec) {
        std::cout << "Stopping server... ";
        server.stop();
        std::cout << "done.\n";
      }
    });

    std::cout << "Press Ctrl+C to stop the server.\n";
    server.run();

    return EXIT_SUCCESS;
  } catch (const std::exception& error) {
    std::cerr << error.what() << std::endl;
    return EXIT_FAILURE;
  }
}
Exemple #7
0
int
main(int argc, char *argv[]) {
  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " <plugins path>" << std::endl;
    return 1;
  }

  PluginDb db;

  db.scan(argv[1]);

  PluginLoader loader(db, argv[1]);

  try {
    std::string path(Utils::getAddress());
    Server server(path, loader);

    boost::asio::signal_set signals(server.service(), SIGQUIT, SIGINT, SIGTERM);
    signals.async_wait([&server](const boost::system::error_code& error,
				 int signal_number) {
			 if (!error) {
			   std::cerr << "signal " << signal_number << ". quitting..." << std::endl;
			   server.shutdown();
			 }
		       });

    server.start();
    return server.loop();
  } catch (std::exception& ex) {
    std::cerr << "Failed to start server: " << ex.what() << std::endl;
    return 1;
  }
}
Exemple #8
0
void sig_handler(int sig)
{
	int ret;

	if (sig == SIGUSR1) {
		mld_query_send();
		return;
	}
	if (sig == SIGUSR2) {
		ret = iface_map_get();
		if (ret < 0)
			goto exit;

		ret = iface_info_glue();
		if (ret < 0)
			goto exit;

		pim_hello_send(NULL);
		return;
	}

exit:
	running = 0;
	signals(SIG_IGN);
	pim_hello_send(NULL);
}
Exemple #9
0
void Server::Run() {
  task_pool->Init(1);

  // Create a pool of threads to run all of the io_services.
  std::vector<boost::shared_ptr<boost::thread> > threads;
  threads.reserve(boost::thread::hardware_concurrency() * 2);
  for (size_t i = 0, n = threads.capacity(); i < n; ++i) {
    boost::shared_ptr<boost::thread> thread(new boost::thread(
      boost::bind(ThreadEntryPoint, &io_service)));
    threads.push_back(thread);
  }

  boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
  signals.async_wait(boost::bind(&Server::handle_signal, shared_from_this(), boost::asio::placeholders::error));

  {
    boost::unique_lock<boost::mutex> lock(signal_mutex);
    while (!stop)
      signal_cv.wait(lock);
  }
  
  task_pool->Stop(true);
  io_service.stop();
  for (size_t i = 0; i < threads.size(); ++i) {
    if (threads[i]->joinable())
      threads[i]->join();
  }
}
Exemple #10
0
Fichier : bm.c Projet : jscrane/lwp
void f (int n)
{
	while (n--)
		yieldp ();
	signals (s);
	suicidep ();
}
int main(int argc,char *argv[])
{
	gtk_init(&argc,&argv);
	initialize();
	signals();
	packing();
	gtk_widget_show_all(window);
	gtk_main();
}
Exemple #12
0
int main(int argc, const char * argv[])
{
    int ret = 0;

    /**
     * Allocate the stack.
     */
    coin::stack s;
    
    std::map<std::string, std::string> args;
    
    for (auto i = 0; i < argc; i++)
    {
        if (argv[i][0] == '-' && argv[i][1] == '-')
        {
            std::string arg = std::string(argv[i]).substr(2, strlen(argv[i]));
            
            std::string key, value;
            
            auto i = arg.find("=");

            if (i != std::string::npos)
            {
                key = arg.substr(0, i);
                
                i = arg.find("=");
                
                if (i != std::string::npos)
                {
                    value = arg.substr(i + 1, strlen(argv[i]));
                    
                    args[key] = value;
                }
            }
        }
    }
    
    /**
     * Start the stack.
     */
    s.start(args);

    /**
     * Wait for termination.
     */
    boost::asio::io_service ios;
    boost::asio::signal_set signals(ios, SIGINT, SIGTERM);
    signals.async_wait(std::bind(&boost::asio::io_service::stop, &ios));
    ios.run();

    /**
     * Stop the stack.
     */
    s.stop();

    return ret;
}
Exemple #13
0
void g ()
{
	int i; char ch=' ';
	for (i=1; i<1000; i++) {
		delayp (350*i);
		write (1, &ch, 1);
	}
	signals (s_end);
	suicidep ();
}
Exemple #14
0
void show_pipeline_pars(){
	int i = 0;
	/// "Параметры конвейера:\n"
	red(_("Pipeline parameters:\n"));
	while(filter_names[i].parname){
		printf("\t%-12s %s\n", filter_names[i].parname, filter_names[i].descr);
		++i;
	}
	signals(9);
}
// init: (speed = B9600 etc)
void tty_init(char *comdev, tcflag_t speed){
    if(comfd == -1){ // not opened
        if(!comdev){
            WARNX("comdev == NULL");
            signals(11);
        }
        DBG("Open port...");
        do{
            comfd = open(comdev,O_RDWR|O_NOCTTY|O_NONBLOCK);
        }while (comfd == -1 && errno == EINTR);
        if(comfd < 0){
            WARN(_("Can't open port %s"),comdev);
            signals(2);
        }
    /*    DBG("OK\nGet current settings...");
        if(ioctl(comfd, TCGETA, &oldtty) < 0){  // Get settings
            /// "Не могу получить настройки"
            WARN(_("Can't get settings"));
            signals(2);
        }*/
        DBG("Make exclusive");
        // make exclusive open
        if(ioctl(comfd, TIOCEXCL)){
            WARN(_("Can't do exclusive open"));
            close(comfd);
            signals(2);
        }
    }
    tty = oldtty;
    tty.c_lflag     = 0; // ~(ICANON | ECHO | ECHOE | ISIG)
    tty.c_oflag     = 0;
    tty.c_cflag     = speed|CS8|CREAD|CLOCAL; // 9.6k, 8N1, RW, ignore line ctrl
    tty.c_cc[VMIN]  = 0;  // non-canonical mode
    tty.c_cc[VTIME] = 5;
    if(ioctl(comfd, TCSETA, &tty) < 0){
        /// "Не могу установить настройки"
        WARN(_("Can't set settings"));
        signals(0);
    }
    DBG("OK");
}
Exemple #16
0
int main(void) try {

    // setup asio::io_service
    std::shared_ptr<boost::asio::io_service> p_io_service(
        std::make_shared<boost::asio::io_service>());

    // Initialize SSL context
    std::shared_ptr<boost::asio::ssl::context> ctx =
        std::make_shared<boost::asio::ssl::context>(
            boost::asio::ssl::context::sslv23);
    ctx->set_options(boost::asio::ssl::context::default_workarounds |
                     boost::asio::ssl::context::no_sslv2 |
                     boost::asio::ssl::context::single_dh_use);

    // Set keys
    ctx->set_password_callback(password_callback);
    ctx->use_certificate_chain_file("server.pem");
    ctx->use_private_key_file("server.pem", boost::asio::ssl::context::pem);
    ctx->use_tmp_dh_file("dh512.pem");

    // setup the async server
    handler request_handler;
    std::shared_ptr<server> p_server_instance(std::make_shared<server>(
                server::options(request_handler)
                .address("0.0.0.0")
                .port("8442")
                .io_service(p_io_service)
                .reuse_address(true)
                .thread_pool(
                    std::make_shared<boost::network::utils::thread_pool>(2))
                .context(ctx)));

    // setup clean shutdown
    boost::asio::signal_set signals(*p_io_service, SIGINT, SIGTERM);
    signals.async_wait([=] (boost::system::error_code const &ec, int signal) {
        shut_me_down(ec, signal, p_server_instance);
    });

    // run the async server
    p_server_instance->run();

    // we are stopped - shutting down

    p_io_service->stop();

    std::cout << "Terminated normally" << std::endl;
    exit(EXIT_SUCCESS);
}
catch (const std::exception& e) {
    std::cout << "Abnormal termination - exception:" << e.what() << std::endl;
    exit(EXIT_FAILURE);
}
// initial setup:
void setup_con(){
    if(console_changed) return;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    if(tcsetattr(STDIN_FILENO, TCSANOW, &newt) < 0){
        /// "Не могу настроить консоль"
        WARN(_("Can't setup console"));
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
        signals(0); //quit?
    }
    console_changed = 1;
}
std::vector<dmod::array1d> getLearningSignals( int signalsAmount, 
											   std::vector<dmod::array1d> input, 
											   std::default_random_engine &gen )
{
	std::vector<dmod::array1d> signals(signalsAmount);
	size_t n = input.size();

	for (auto iter = signals.begin(); iter != signals.end(); ++iter)
	{
		size_t x = gen() % n;
		*iter = input[x];
	}

	return std::move(signals);
}
Exemple #19
0
int		main(int ac, char **av, char **env)
{
	t_cmd	cmd;
	t_dict	*dicts[DICT_COUNT];

	(void)ac;
	(void)av;
	init_tokens(&dicts[TOKENS]);
	init_binaries(&dicts[BIN]);
	dicts[ENV] = envcpy(env);
	signals();
	interpret_command(dicts, &cmd);
	destroy_array_dict(dicts, DICT_COUNT);
	cmd_free(&cmd);
	return (0);
}
std::vector<dmod::array1d> getLearningSignals( int signalsAmount, 
											   dmod::Tomogram &tomo, 
											   std::default_random_engine &gen )
{
	std::vector<dmod::array1d> signals(signalsAmount);
	size_t h = tomo.getHeight();
	size_t w = tomo.getWidth();

	for (auto iter = signals.begin(); iter != signals.end(); ++iter)
	{
		size_t y = gen() % h;
		size_t x = gen() % w;
		*iter = tomo.getSignal1D(x, y, 0, dmod::Axis::Z);
	}

	return signals;
}
Exemple #21
0
static void init_everything() {
	struct timespec ts;

	clock_gettime(CLOCK_REALTIME, &ts);
	srandom(ts.tv_sec ^ ts.tv_nsec);
	SSL_library_init();
	SSL_load_error_strings();

#if !GLIB_CHECK_VERSION(2,32,0)
	g_thread_init(NULL);
#endif
	if (!_log_stderr)
		openlog("rtpengine", LOG_PID | LOG_NDELAY, _log_facility);
	signals();
	resources();
	sdp_init();
	dtls_init();
}
Exemple #22
0
/**
 * Run daemon service
 */
void daemonize(char *port){
    FNAME();
    int sock = -1;
    struct addrinfo hints, *res, *p;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if(getaddrinfo(NULL, port, &hints, &res) != 0){
        ERR("getaddrinfo");
    }
    struct sockaddr_in *ia = (struct sockaddr_in*)res->ai_addr;
    char str[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(ia->sin_addr), str, INET_ADDRSTRLEN);
    // loop through all the results and bind to the first we can
    for(p = res; p != NULL; p = p->ai_next){
        if((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1){
            WARN("socket");
            continue;
        }
        int reuseaddr = 1;
        if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1){
            ERR("setsockopt");
        }
        if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
            close(sock);
            WARN("bind");
            continue;
        }
        break; // if we get here, we have a successfull connection
    }
    if(p == NULL){
        putlog("failed to bind socket, exit");
        // looped off the end of the list with no successful bind
        ERRX("failed to bind socket");
    }
    freeaddrinfo(res);
    daemon_(sock);
    close(sock);
    putlog("socket closed, exit");
    signals(0);
}
Exemple #23
0
int main(int argc, char* argv[])
{
  try
  {
    // Check command line arguments.
    if (argc != 4)
    {
      std::cerr << "Usage: http_server <address> <port> <doc_root>\n";
      std::cerr << "  For IPv4, try:\n";
      std::cerr << "    receiver 0.0.0.0 80 .\n";
      std::cerr << "  For IPv6, try:\n";
      std::cerr << "    receiver 0::0 80 .\n";
      return 1;
    }

    boost::asio::io_service io_service;

    // Launch the initial server coroutine.
    http::server4::server(io_service, argv[1], argv[2],
        http::server4::file_handler(argv[3]))();

    // Wait for signals indicating time to shut down.
    boost::asio::signal_set signals(io_service);
    signals.add(SIGINT);
    signals.add(SIGTERM);
#if defined(SIGQUIT)
    signals.add(SIGQUIT);
#endif // defined(SIGQUIT)
    signals.async_wait(boost::bind(
          &boost::asio::io_service::stop, &io_service));

    // Run the server.
    std::cout << "Running the server." << std::endl;
    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "exception: " << e.what() << "\n";
  }

  return 0;
}
Exemple #24
0
    void run(int, char*const[])
    {
        /// setup(Args(ac, av));

        boost::asio::signal_set signals(io_service(), SIGINT, SIGTERM);
        signals.async_wait([this](boost::system::error_code const&, int) {
                this->teardown();
            });

        for (auto& t : thread_) {
            t = std::thread([this]{ io_service().run(); });
        }
        LOG(INFO) << thread_.size() << "threads";

        for (auto& t : thread_) {
            t.join();
            LOG(ERROR) << "joined" << int(&t - &thread_.front());
        }
        LOG(ERROR) << "bye.";
    }
Exemple #25
0
int main(int argc,char ** argv)
{

  TApplication application("app",&argc,argv);

  Signals::SignalSet signals("Meine Signale");
  Signals::Signal a(3.125);
  Signals::Signal b(3.125);
  a.SetSignalLength(200);
  b.SetSignalLength(200);
  a.CreateHeaviside(100,-1,1);
  b.CreateHeaviside(150,-2,2);

  unsigned int index=signals.SetSignal(-1,"signal",a);
  signals.SetSignal(index,"b",b);

  Tools::ASCIIOutStream streamout("test.sig");
  streamout<<signals;
  
  Tools::ASCIIInStream streamin("test.sig");
  Signals::SignalSet sigtest("Test");
  streamin>>sigtest;
  Signals::Signal& ra=sigtest.GetSignal(0,"signal");
  Signals::Signal& rb=sigtest.GetSignal(0,"b");

  TCanvas * canvas1=new TCanvas;
  a.Graph()->Draw("AL*");
  canvas1->Update();

  TCanvas * canvas2=new TCanvas;
  b.Graph()->Draw("AL*");
  canvas2->Update();

  application.Run(kTRUE);

  return 0;
}
Exemple #26
0
int main(int argc, char **argv) {
    asio::io_service ios;

    // Register signal handler to stop the io_service
    asio::signal_set signals(ios, SIGINT, SIGTERM);
    signals.async_wait([&](const boost::system::error_code &, int) { ios.stop(); });

    // Connect to task ventilator
    aziomq::socket receiver(ios, ZMQ_PULL);
    receiver.connect("tcp://localhost:5556");

    // schedule receiver socket
    std::array<char, 4096> task;
    receiver.async_receive(asio::buffer(task), [&](const boost::system::error_code & ec,
                                                   size_t bytes_transferred) {
            if (!ec) {
                // process task
            }
    });

    // Connect to weather server
    aziomq::socket subscriber(ios, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");
    subscriber.set_option(aziomq::socket::subscribe("10001 "));

    // schedule weather updates
    std::array<char, 4096> update;
    subscriber.async_receive(asio::buffer(task), [&](const boost::system::error_code & ec,
                                                     size_t bytes_transferred) {
            if (!ec) {
                // process weather update
            }
    });
    ios.run();
    return 0;
}
Exemple #27
0
int main(int argc, char **argv)
{
	int			ret = EX_OK;
	int			i;
	struct group		*grgid;
	struct passwd		*pwuid;
	timer_t			timerid_mld, timerid_pim;
	struct pollfd		fds[4];
	nfds_t			nfds = 0;
	struct sockaddr_storage	from, to;
	socklen_t		addrlen = sizeof(struct sockaddr_storage);
	unsigned int		from_ifindex;
	char			*buf;

	ret = parse_args(argc, argv);
	if (ret)
		return -ret;

	if (getuid()) {
		fprintf(stderr, "need to run as root\n");
		return EX_NOPERM;
	}

	if (!nofork) {
		pid_t pid = fork();

		if (pid < 0) {
			perror("fork()");
			return EX_OSERR;
		} else if (pid > 0)
			return EX_OK;

		if (setsid() < 0) {
			perror("setsid()");
			return EX_OSERR;
		}

		if (chdir("/") < 0) {
			perror("chdir(\"/\")");
			return EX_OSERR;
		}

		openlog(basename(argv[0]), LOG_PID, LOG_DAEMON);
	} else
		openlog(basename(argv[0]), LOG_PID | LOG_PERROR, LOG_DAEMON);
	setlogmask(LOG_UPTO(debug));

	logger(LOG_NOTICE, 0, "started");

	errno = 0;
	mroute4 = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP);
	if (mroute4 >= 0) {
		if (pktinfo(mroute4) < 0) {
			close(mroute4);
			mroute4 = -1;
		} else {
			pim4 = pim_init(mroute4);
			if (pim4 < 0) {
				close(mroute4);
				mroute4 = -1;
			} else {
				add_poll(fds, &nfds, mroute4);
				add_poll(fds, &nfds, pim4);
			}
		}
	}
	if (mroute4 < 0)
		logger(LOG_WARNING, errno, "no IPv4 support");
	errno = 0;
	mroute6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
	if (mroute6 >= 0) {
		if (pktinfo(mroute6) < 0) {
			close(mroute6);
			mroute6 = -1;
		} else {
			pim6 = pim_init(mroute6);
			if (pim6 < 0) {
				close(mroute6);
				mroute6 = -1;
			} else {
				add_poll(fds, &nfds, mroute6);
				add_poll(fds, &nfds, pim6);
			}
		}
	}
	if (mroute6 < 0)
		logger(LOG_WARNING, errno, "no IPv6 support");

	if (mroute4 < 0 && mroute6 < 0) {
		logger(LOG_ERR, 0, "multicast routing unavailable");
		ret = -EX_OSERR;
		goto exit;
	}

	ret = route_init();
	if (ret)
		goto mroute;

	errno = 0;
	grgid = getgrnam(gid);
	if (grgid) {
		if (setgid(grgid->gr_gid))
			logger(LOG_WARNING, errno, "unable to drop group privileges");
	} else
		logger(LOG_WARNING, errno, "unable to find group '%s' to drop privileges to", gid);
	errno = 0;
	pwuid = getpwnam(uid);
	if (pwuid) {
		if (setuid(pwuid->pw_uid))
			logger(LOG_WARNING, errno, "unable to drop user privileges");
	} else
		logger(LOG_WARNING, errno, "unable to find user '%s' to drop privileges to", uid);

	ret = signals(&sig_handler);
	if (ret)
		goto route;

	ret = prime_timers(&timerid_mld, &timerid_pim);
	if (ret)
		goto signal;

	buf = malloc(SOCK_BUFLEN);
	if (buf == NULL) {
		logger(LOG_ERR, 0, "malloc()");
		ret = -EX_OSERR;
		goto timer;
	}

	while (running) {
		ret = poll(fds, nfds, -1);
		if (ret == -1) {
			if (errno == EINTR)
				continue;

			logger(LOG_ERR, errno, "poll()");
			ret = -EX_OSERR;
			running = 0;
			continue;
		}

		for (i = 0; i < nfds; i++) {
			/* TODO handle errors */
			assert(!(fds[i].revents & (POLLERR | POLLHUP)));

			/* either a non-event or there is something to read */
			assert(!fds[i].revents || fds[i].revents & POLLIN);

			if (!fds[i].revents)
				continue;

			if (fds[i].revents & POLLIN) {
				ret = recvfromto(fds[i].fd, buf, SOCK_BUFLEN, 0,
						(struct sockaddr *)&from,
						(struct sockaddr *)&to,
						&addrlen, &from_ifindex);
				if (ret == -1)
					continue;

				if (fds[i].fd == pim4 || fds[i].fd == pim6)
					pim_recv(fds[i].fd, buf, ret,
							&from, &to, addrlen,
							from_ifindex);
				else
					mld_recv(fds[i].fd, buf, ret,
							&from, &to, addrlen,
							from_ifindex);
			}
		}
	}

	free(buf);

timer:
	timer_delete(timerid_mld);
	timer_delete(timerid_pim);
signal:
	signals(SIG_IGN);
route:
	route_shutdown();
mroute:
	if (mroute4 > 0) {
		close(pim4);
		pim_shutdown(mroute4);
	}
	if (mroute6 > 0) {
		close(pim6);
		pim_shutdown(mroute6);
	}
exit:
	logger(LOG_NOTICE, 0, "exiting");

	closelog();

	assert(ret <= 0);

	return -ret;
}
Exemple #28
0
int main(int argc, char** argv)
{
  std::ostringstream oss;
  oss << "Usage: " << argv[0] << " [additional options]";
  po::options_description desc(oss.str());
  desc.add_options()
    ("help,h", "produce this message")
    ("debug,d", "enable debug mode")
    ("logfile,l", po::value<std::string>(), "set the logfile to use")
    ("interval,i", po::value<int>(), "set the broadcast interval")
    ("interface,I", po::value<std::vector<std::string> >(), "interface to use for multicast")
    ("address,a", po::value<std::vector<std::string> >(), "address to listen on")
    ;
  po::variables_map vm;

  // Begin processing of commandline parameters.
  try {
    po::store(po::command_line_parser(argc, argv).
        options(desc).run(), vm);
    po::notify(vm);
  } catch (std::exception& e) {
    std::cerr << "Cannot process commandline options: " << e.what() << std::endl;
    exit(-1);
  }

  bool debug = false;
  std::string logfile = "/tmp/hexadaemon.log";
  int interval = 2;
  std::vector<std::string> interfaces;
  std::vector<std::string> addresses;

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return 1;
  }

  if (vm.count("debug")) {
    std::cout << "debug enabled" << std::endl;
    debug = true;
  }

  if (vm.count("logfile")) {
    logfile = vm["logfile"].as<std::string>();
    debug && std::cout << "logfile: " << logfile << std::endl;
  }

  if (vm.count("interval")) {
    interval = vm["interval"].as<int>();
    std::cout << "interval: " << interval << std::endl;
  }

  if (vm.count("interface")) {
    interfaces = vm["interface"].as<std::vector<std::string> >();
    for (std::vector<std::string>::iterator it = interfaces.begin(); it != interfaces.end(); ++it)
      debug && std::cout << "interface: " << *it << std::endl;
  } else {
    std::cerr << "You have to specify at least one interface." << std::endl;
    return 1;
  }


  if (vm.count("address")) {
    addresses = vm["address"].as<std::vector<std::string> >();
    for (std::vector<std::string>::iterator it = addresses.begin(); it != addresses.end(); ++it)
      debug && std::cout << "address: " << *it << std::endl;
  } else {
    std::cerr << "You have to specify at least one address." << std::endl;
    return 1;
  }

  try
  {
    boost::asio::io_service io_service;

    // Initialise the server before becoming a daemon. If the process is
    // started from a shell, this means any errors will be reported back to the
    // user.
    //udp_daytime_server server(io_service);
    hexadaemon::HexabusServer *server;
    server = new hexadaemon::HexabusServer(io_service, interfaces, addresses, interval, debug);

    // Register signal handlers so that the daemon may be shut down. You may
    // also want to register for other signals, such as SIGHUP to trigger a
    // re-read of a configuration file.
    boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
    signals.async_wait(
      boost::bind(&boost::asio::io_service::stop, &io_service));

    if ( !debug ) {
      // Inform the io_service that we are about to become a daemon. The
      // io_service cleans up any internal resources, such as threads, that may
      // interfere with forking.
      io_service.notify_fork(boost::asio::io_service::fork_prepare);

      // Fork the process and have the parent exit. If the process was started
      // from a shell, this returns control to the user. Forking a new process is
      // also a prerequisite for the subsequent call to setsid().
      if (pid_t pid = fork())
      {
        if (pid > 0)
        {
          // We're in the parent process and need to exit.
          //
          // When the exit() function is used, the program terminates without
          // invoking local variables' destructors. Only global variables are
          // destroyed. As the io_service object is a local variable, this means
          // we do not have to call:
          //
          //   io_service.notify_fork(boost::asio::io_service::fork_parent);
          //
          // However, this line should be added before each call to exit() if
          // using a global io_service object. An additional call:
          //
          //   io_service.notify_fork(boost::asio::io_service::fork_prepare);
          //
          // should also precede the second fork().
          exit(0);
        }
        else
        {
          syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
          return 1;
        }
      }

      // Make the process a new session leader. This detaches it from the
      // terminal.
      setsid();

      // A process inherits its working directory from its parent. This could be
      // on a mounted filesystem, which means that the running daemon would
      // prevent this filesystem from being unmounted. Changing to the root
      // directory avoids this problem.
      chdir("/");

      // The file mode creation mask is also inherited from the parent process.
      // We don't want to restrict the permissions on files created by the
      // daemon, so the mask is cleared.
      umask(0);

      // A second fork ensures the process cannot acquire a controlling terminal.
      if (pid_t pid = fork())
      {
        if (pid > 0)
        {
          exit(0);
        }
        else
        {
          syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
          return 1;
        }
      }

      // Close the standard streams. This decouples the daemon from the terminal
      // that started it.
      close(0);
      close(1);
      close(2);

      // We don't want the daemon to have any standard input.
      if (open("/dev/null", O_RDONLY) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m");
        return 1;
      }

      // Send standard output to a log file.
      const char* output = logfile.c_str();
      const int flags = O_WRONLY | O_CREAT | O_APPEND;
      const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
      if (open(output, flags, mode) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output);
        return 1;
      }

      // Also send standard error to the same log file.
      if (dup(1) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m");
        return 1;
      }

      // Inform the io_service that we have finished becoming a daemon. The
      // io_service uses this opportunity to create any internal file descriptors
      // that need to be private to the new process.
      io_service.notify_fork(boost::asio::io_service::fork_child);

      // The io_service can now be used normally.
      syslog(LOG_INFO | LOG_USER, "HexabusDaemon started");
    }
    io_service.run();
    if ( !debug )
      syslog(LOG_INFO | LOG_USER, "HexabusDaemon stopped");
  }
  catch (hexabus::NetworkException& e)
  {
    std::cerr << "An error occured during " << e.reason() << ": " << e.code().message() << std::endl;
  }
  catch (hexabus::GenericException& e)
  {
    std::cerr << "An error occured during " << e.reason() << std::endl;
  }
  catch (boost::exception& e)
  {
    std::cerr << "Boost Exception: " << diagnostic_information(e) << std::endl;
  }
  catch (std::exception& e)
  {
    syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what());
    std::cerr << "Exception: " << e.what() << std::endl;
  }
}
Exemple #29
0
int main(int argc, char* argv[])
{
//  try
//  {

    std::string localhost("127.0.0.1");
    std::string localport("9998");
    std::string remotehost("127.0.0.1");
    std::string remoteport("9998");

    std::cout << "argc: " << argc << "\n";
    /// @todo add default localhost/localport
    if (argc != 5 && argc != 1 && argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
        return 1;
    }

    bool shouldReceive = true;

    if(argc == 3) {
        remotehost = std::string(argv[1]);
        remoteport = std::string(argv[2]);
        shouldReceive = false;
    }

    if(argc == 5) {
        localhost = std::string(argv[1]);
        localport = std::string(argv[2]);
        remotehost = std::string(argv[3]);
        remoteport = std::string(argv[4]);
        shouldReceive = true;
    }

    std::cout << "using: "  << argv[0] << " ";
    if(shouldReceive) std::cout <<  localhost << " " << localport << " ";
    std::cout <<  remotehost << " " << remoteport << "\n";
    boost::asio::io_service io_service;


    // Register signal handlers so that the daemon may be shut down when a signal is received.
    boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
    signals.async_wait( std::bind(&boost::asio::io_service::stop, &io_service));
#if 0
    std::shared_ptr<AzmqFlatbuffer> sendP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.connect("tcp://"+ remotehost + ":" + remoteport);
        sendP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }
    std::shared_ptr<AzmqFlatbuffer> receiveP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.bind("tcp://" + localhost + ":" + localport);
        receiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }

    // Will run until signal is received, using separate objects for send and receive
    std::thread t(bounce,sendP,receiveP);
#else

    std::shared_ptr<AzmqFlatbuffer> receiveP;
    {
        boost::system::error_code ec;
        azmq::socket socket(io_service, ZMQ_DEALER);
        socket.bind("tcp://" + localhost + ":" + localport);
        socket.connect("tcp://"+ remotehost + ":" + remoteport);
        receiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));
    }

    // Will run until signal is received, using one object for both send and receive
    std::thread t(bounce,receiveP,receiveP,shouldReceive);
#endif

    io_service.run();

    t.join();

//  }
//  catch (std::exception& e)
//  {
//    std::cerr << "Exception: " << e.what() << "\n";
//  }

    return 0;
}
Exemple #30
0
// **********************************************************************
// **********************************************************************
// dispatch curTask
//
static int dispatcher()
{
	int result;

	// schedule task
	switch(tcb[curTask].state)
	{
		case S_NEW:
		{
			// new task
			printf("\nNew Task[%d] %s", curTask, tcb[curTask].name);
			tcb[curTask].state = S_RUNNING;	// set task to run state

			// save kernel context for task SWAP's
			if (setjmp(k_context))
			{
				superMode = TRUE;					// supervisor mode
				break;								// context switch to next task
			}

			// move to new task stack (leave room for return value/address)
			temp = (int*)tcb[curTask].stack + (STACK_SIZE-8);
			SET_STACK(temp);
			superMode = FALSE;						// user mode

			// begin execution of new task, pass argc, argv
			result = (*tcb[curTask].task)(tcb[curTask].argc, tcb[curTask].argv);

			// task has completed
			if (result) printf("\nTask[%d] returned %d", curTask, result);
			else printf("\nTask[%d] returned %d", curTask, result);
			tcb[curTask].state = S_EXIT;			// set task to exit state

			// return to kernal mode
			longjmp(k_context, 1);					// return to kernel
		}

		case S_READY:
		{
			tcb[curTask].state = S_RUNNING;			// set task to run
		}

		case S_RUNNING:
		{
			if (setjmp(k_context))
			{
				// SWAP executed in task
				superMode = TRUE;					// supervisor mode
				break;								// return from task
			}
			if (signals()) break;
			longjmp(tcb[curTask].context, 3); 		// restore task context
		}

		case S_BLOCKED:
		{
			// ?? Could check here to unblock task
			break;
		}

		case S_EXIT:
		{
			if (curTask == 0) return -1;			// if CLI, then quit scheduler
			// release resources and kill task
			sysKillTask(curTask);					// kill current task
			break;
		}

		default:
		{
			printf("Unknown Task[%d] State", curTask);
			longjmp(reset_context, POWER_DOWN_ERROR);
		}
	}
	return 0;
} // end dispatcher