int main(int argc, char** argv){ int sd; sd=0; if(argc != 2) { printf("Please enter the name of the machine running the server process as a command line argument.\n"); exit(1); } /*try to connect to the server every three seconds*/ while((sd = serverconnect(argv[1], "36963")) == -1) { sleep(3); } /*Section 8, requirement 1 - announce completion of connection to server*/ printf("Success! Client connected to server.\n"); /*spawn threads*/ /*lmao now what*/ spawn_threads(sd); close(sd); /*Disconnect from server*/ printf("Client has disconnected from the server.\n"); return 0; /*success*/ }
int main(int argc, char *argv[]) { OCIError *errhp = NULL; printf("stage4: Demonstrating OCI statement caching \n"); /* parse command line options */ parse_options(argc, argv); checkenv(envhp, OCIEnvCreate(&envhp, /* returned env handle */ OCI_THREADED, /* initialization modes */ NULL, NULL, NULL, NULL, /* callbacks, context */ (size_t) 0, /* extra memory size: optional */ (void **) NULL)); /* returned extra memory */ /* allocate error handle * note: for OCIHandleAlloc(), we always check error on environment handle */ checkenv(envhp, OCIHandleAlloc(envhp, /* environment handle */ (void **) &errhp, /* returned err handle */ OCI_HTYPE_ERROR,/*type of handle to allocate*/ (size_t) 0, /* extra memory size: optional */ (void **) NULL)); /* returned extra memory */ create_session_pool(envhp, errhp, &poolName, &poolNameLen); /* allocate auth handle * note: for OCIHandleAlloc(), we check error on environment handle */ checkenv(envhp, OCIHandleAlloc(envhp, (void **) &authp, OCI_HTYPE_AUTHINFO, (size_t) 0, (void **) NULL)); /* setup username and password */ checkerr(errhp, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO, (void *) username, strlen((char *)username), OCI_ATTR_USERNAME, errhp)); checkerr(errhp, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO, apppassword, strlen((char *) apppassword), OCI_ATTR_PASSWORD, errhp)); spawn_threads(envhp, errhp, &thread_function); /* Destroy the session pool */ OCISessionPoolDestroy(spoolhp, errhp, OCI_DEFAULT); /* clean up */ if (authp) OCIHandleFree(authp, OCI_HTYPE_AUTHINFO); if (spoolhp) OCIHandleFree(spoolhp, OCI_HTYPE_SPOOL); if (errhp) OCIHandleFree(errhp, OCI_HTYPE_ERROR); if (envhp) OCIHandleFree(envhp, OCI_HTYPE_ENV); return 0; }
void test_histogram__sampling(void) { struct histo_test test; memset(&test.h, 0x0, sizeof(test.h)); pthread_spin_init(&test.lock, 0); spawn_threads(&thread_histo, &test); }
int main() { srand(time(NULL)); for(int i = 0; i < INPUT_SIZE; i++) { // check[i] = input[i] = rand()%2; } newLimit = ceil(log2(NUM_THREADS)); double sTime, pTime; struct timeval tz; struct timezone tx; double start_time, end_time; gettimeofday(&tz, &tx); start_time = (double)tz.tv_sec + (double) tz.tv_usec / 1000000.0; spawn_threads(input, INPUT_SIZE, NUM_THREADS); gettimeofday(&tz, &tx); end_time = (double)tz.tv_sec + (double) tz.tv_usec / 1000000.0; pTime = end_time-start_time; printf("Parallel Time: time_p - %lf\n", pTime); /* for(int i = 0; i < sumLimit; i++){ printf("%d ",sum[i]); } printf("\n"); */ gettimeofday(&tz, &tx); start_time = (double)tz.tv_sec + (double) tz.tv_usec / 1000000.0; for(int i = 1; i < INPUT_SIZE; i++) { check[i] += check[i-1]; } gettimeofday(&tz, &tx); end_time = (double)tz.tv_sec + (double) tz.tv_usec / 1000000.0; sTime = end_time-start_time; printf("Serial Time: time_s - %lf\n", sTime); for(int i=0;i<INPUT_SIZE;i++){ if(input[i] != check[i]){ printf("------FAIL:%d %d-------\n",input[i], check[i]); } // printf("%d %d\n",input[i], check[i]); } printf("Speedup: %lf\n",(double)sTime/pTime); return EXIT_SUCCESS; }
void HostInternal::initialize( const unsigned gang_count , const unsigned worker_count ) { const bool ok_inactive = 1 == m_thread_count ; const bool ok_gang_count = gang_count <= m_node_count ; const bool ok_worker_count = ( 0 == m_node_pu_count || worker_count <= m_node_pu_count ); // Only try to spawn threads if input is valid. const bool ok_spawn_threads = ( ok_inactive && ok_gang_count && ok_worker_count && 1 < gang_count * worker_count ) ? spawn_threads( gang_count , worker_count ) : true ; if ( ! ok_inactive || ! ok_gang_count || ! ok_worker_count || ! ok_spawn_threads ) { std::ostringstream msg ; msg << "KokkosArray::Host::initialize() FAILED" ; if ( ! ok_inactive ) { msg << " : Device is already active" ; } if ( ! ok_gang_count ) { msg << " : gang_count(" << gang_count << ") exceeds detect_node_count(" << m_node_count << ")" ; } if ( ! ok_worker_count ) { msg << " : worker_count(" << worker_count << ") exceeds detect_node_pu_count(" << m_node_pu_count << ")" ; } if ( ! ok_spawn_threads ) { msg << " : Spawning or cpu-binding the threads" ; } throw std::runtime_error( msg.str() ); } }
void smooth_parallel(Mesh* mesh, int niter){ //Colouring phase int colour = 0; vertices = mesh->NNodes; populate_vertices( mesh ); while( vertices > 0 ){ std::vector<int> v; slices.push_back(v); select_vertices( mesh, colour ); colour++; } printf("Colours: %d\n", colour); delete[] vertices_in_neighberhood; delete[] to_examine_all; //Execution phase svd_init( mesh->NNodes ); double * quality_cache = new double[mesh->NElements]; bool * vertice_in_cache = new bool[mesh->NElements]; memset(quality_cache, 0, mesh->NElements); memset(vertice_in_cache, false, mesh->NElements); for(int iter = 0; iter < niter; iter++){ for(size_t c = 0; c < colour; c++){ spawn_threads( mesh, c, quality_cache, vertice_in_cache, iter ); } } svd_teardown( mesh->NNodes ); delete[] quality_cache; delete[] vertice_in_cache; }
int main(int argc, char *argv[]) { int number_of_threads{0}; std::string directory; ssfi::parse_args(argc, argv, number_of_threads, directory); boost::filesystem::path path(directory); ssfi::check_directory(path); BOOST_LOG_TRIVIAL(info) << "Finding text files under " << directory; BOOST_LOG_TRIVIAL(info) << "Number of worker threads to read in text " << "files: " << number_of_threads; //std::shared_ptr<WorkerQueue> worker_queue_ptr = auto worker_queue_ptr = std::make_shared<ssfi::BoostAsIOQueue>(number_of_threads); worker_queue_ptr->spawn_threads(); ssfi::FileLocator file_locator{".txt", worker_queue_ptr}; // Requirement 2: start up a thread to find all of the files passed in via // a command line argument boost::thread find_files(&ssfi::FileLocator::recursively_find_files, &file_locator, path); find_files.join(); worker_queue_ptr->clear(); worker_queue_ptr->join(); BOOST_LOG_TRIVIAL(trace) << "Worker queue finished"; const auto count_word_map = file_locator.get_parser().get_count_word_map(); BOOST_LOG_TRIVIAL(trace) << "length of map = " << count_word_map.size(); ssfi::print_top_words(10, count_word_map); return 0; }
int net_deploy (void) { if (((int) net_opts.thread_l + (int) net_opts.thread_r) > net_opts.max_worker_threads) { print_str ( "ERROR: net_deploy: requested thread count exceeds 'max_worker_threads' [%d/%d]\n", ((int) net_opts.thread_l + (int) net_opts.thread_r), net_opts.max_worker_threads); return -1; } //_m_tid = getpid(); /*#ifdef M_ARENA_TEST mallopt (M_ARENA_TEST, 1); #endif*/ #ifdef M_ARENA_MAX mallopt (M_ARENA_MAX, 1); #endif struct sigaction sa_wthrd, sa_mthrd; sa_wthrd.sa_handler = sig_handler_null; sa_wthrd.sa_flags = SA_RESTART; sigfillset (&sa_wthrd.sa_mask); //sigaddset(&sa_wthrd.sa_mask, SIGIO); //sigaddset(&sa_wthrd.sa_mask, SIGUSR1); sigaction (SIGIO, &sa_wthrd, NULL); sigaction (SIGURG, &sa_wthrd, NULL); sigaction (SIGUSR1, &sa_wthrd, NULL); sa_mthrd.sa_handler = net_def_sig_handler; sa_mthrd.sa_flags = SA_RESTART; sigfillset (&sa_mthrd.sa_mask); //sigaddset(&sa_mthrd.sa_mask, SIGUSR2); sigaction (SIGUSR2, &sa_mthrd, NULL); sigset_t set; sigemptyset (&set); sigaddset (&set, SIGPIPE); sigaddset (&set, SIGURG); sigaddset (&set, SIGIO); sigaddset (&set, SIGUSR1); sigaddset (&set, SIGHUP); int sr = pthread_sigmask (SIG_BLOCK, &set, NULL); uint32_t in_f = 0; if (sr != 0) { print_str ("ERROR: net_deploy: pthread_sigmask failed: %d\n", sr); abort (); } md_init_le (&_sock_r, (int) net_opts.max_sock); md_init_le (&_net_thrd_r, (int) net_opts.max_worker_threads); //md_init_le (&_thrd_r_common, 32); md_init_le (&tasks_in, MAX_TASKS_GLOBAL); md_init_le (&fs_jobs, 1024); if (net_opts.flags & F_NETOPT_SSLINIT) { print_str ("DEBUG: initializing TLS/SSL subsystem..\n"); ssl_init (); in_f |= F_ND_SSL_INIT; } int r; po_thrd task_worker_object; if ((r = thread_create (task_worker, 0, NULL, 0, 0, F_THRD_NOWPID | F_THRD_NOREG, F_THC_SKIP_IO, NULL, &task_worker_object, NULL))) { return r; } if ((r = spawn_threads (net_opts.thread_l, net_worker, 0, &_net_thrd_r, THREAD_ROLE_NET_WORKER, SOCKET_OPMODE_LISTENER, 0))) { print_str ("ERROR: spawn_threads failed [SOCKET_OPMODE_LISTENER]: %d\n", r); return 2; } else { print_str ( "DEBUG: deployed %hu socket worker threads [SOCKET_OPMODE_LISTENER]\n", net_opts.thread_l); } if ((r = spawn_threads (net_opts.thread_r, net_worker, 0, &_net_thrd_r, THREAD_ROLE_NET_WORKER, SOCKET_OPMODE_RECIEVER, 0))) { print_str ("ERROR: spawn_threads failed [SOCKET_OPMODE_RECIEVER]: %d\n", r); return 2; } else { print_str ( "DEBUG: deployed %hu socket worker threads [SOCKET_OPMODE_RECIEVER]\n", net_opts.thread_r); } print_str ("DEBUG: waiting for workers to initialize..\n"); if (net_deploy_wait_for_all_threads (&_net_thrd_r)) { print_str ("D5: all workers online\n"); } else { goto _t_kill; } int fail; if ((fail = process_ca_requests (&_boot_pca, F_OPSOCK_LISTEN))) { if ((off_t) fail == _boot_pca.offset) { print_str ( "WARNING: process_ca_requests: no socket requests succeeded\n"); goto _t_kill; } else { print_str ( "WARNING: process_ca_requests: not all socket requests were succesfull\n"); } } else { print_str ("DEBUG: deployed %llu listener socket(s)\n", (uint64_t) _boot_pca.offset); } if (fs_jobs.offset) { __gfs job = (__gfs ) fs_jobs.first->ptr; if (job->id < 1 || job->id > USHRT_MAX) { print_str ("ERROR: invalid job id\n"); goto _ts_kill; } if (NULL == job->link || !strlen (job->link)) { print_str ("ERROR: job [%d] has no path\n", job->id); goto _ts_kill; } int ret; if (!(ret = fs_link_socks_to_job (job, &_sock_r))) { print_str ("ERROR: job [%d] defined but no sockets link to it\n", job->id); goto _ts_kill; } //job->status |= FS_GFS_JOB_LOPEN; print_str ("DEBUG: %d sockets linked to job [%d]\n", ret, job->id); if ((r = spawn_threads (1, fs_worker, 0, &_net_thrd_r, THREAD_ROLE_FS_WORKER, 0, 0))) { print_str ( "ERROR: spawn_threads failed [SOCKET_OPMODE_LISTENER]: %d\n", r); return 2; } if (!net_deploy_wait_for_all_threads (&_net_thrd_r)) { print_str ("ERROR: could not spawn fs_worker thread\n"); goto _t_kill; } } if (net_opts.flags & F_NETOPT_CHROOT) { if (chroot (net_opts.chroot) == -1) { char err_buf[1024]; print_str ( "ERROR: netctl_opt_parse: '%s': chroot failed: [%d] [%s]\n", net_opts.chroot, errno, strerror_r (errno, err_buf, sizeof(err_buf))); goto _ts_kill; } print_str ("NOTICE: chrooted %s\n", net_opts.chroot); } if (net_opts.flags & F_NETOPT_GID) { if (setgid (net_opts.gid) == -1) { char e_buffer[1024]; print_str ("ERROR: setgid failed: %s\n", strerror_r (errno, e_buffer, sizeof(e_buffer))); goto _ts_kill; } else { print_str ("DEBUG: setgid: %u\n", (unsigned int) net_opts.gid); } } if (net_opts.flags & F_NETOPT_UID) { if (setuid (net_opts.uid) == -1) { char e_buffer[1024]; print_str ("ERROR: setuid failed: %s\n", strerror_r (errno, e_buffer, sizeof(e_buffer))); goto _ts_kill; } else { print_str ("DEBUG: setuid: %u\n", (unsigned int) net_opts.uid); } } if (net_opts.flags & (F_NETOPT_HUSER | F_NETOPT_HGROUP)) { if (net_opts.flags & F_NETOPT_HUSER) { snprintf (G_USER, sizeof(G_USER), "%s", net_opts.user); gfl0 |= F_OPT_SETUID; } if (net_opts.flags & F_NETOPT_HGROUP) { snprintf (G_GROUP, sizeof(G_GROUP), "%s", net_opts.group); gfl0 |= F_OPT_SETGID; } g_setxid (); } //htest(); if ( NULL != ftp_cmd) { net_ftp_init (ftp_cmd); } net_pop_rc (NULL, &net_post_init_rc); thread_broadcast_sig (&_net_thrd_r, SIGINT); if ((fail = process_ca_requests (&_boot_pca, F_OPSOCK_CONNECT))) { if ((off_t) fail == _boot_pca.offset) { print_str ( "WARNING: process_ca_requests: no socket requests succeeded\n"); goto _t_kill; } else { print_str ( "WARNING: process_ca_requests: not all socket requests were succesfull\n"); } } while (g_get_gkill ()) { //net_ping_threads(); sleep (-1); } _ts_kill: ; if (register_count (&_sock_r)) { print_str ("DEBUG: sending F_OPSOCK_TERM to all sockets\n"); net_nw_ssig_term_r (&_sock_r); } _t_kill: ; print_str ("DEBUG: sending F_THRD_TERM to all worker threads\n"); thread_broadcast_kill (&_net_thrd_r); print_str ("DEBUG: waiting for threads to exit..\n"); if ((r = thread_join_threads (&_net_thrd_r))) { print_str ("WARNING: %d threads remaining\n", r); } thread_send_kill (task_worker_object); pthread_join (task_worker_object->pt, NULL); md_g_free_l (&_net_thrd_r); md_g_free_l (&_sock_r); free (pc_a.objects); md_g_free_l (&_boot_pca); md_g_free_l (&tasks_in); md_g_free_l (&fs_jobs); if (in_f & F_ND_SSL_INIT) { print_str ("DEBUG: releasing TLS/SSL resources..\n"); ssl_cleanup (); } print_str ("INFO: server shutting down..\n"); return 0; }
void *thread_fn_01(void *arg) { int i; unsigned char buf[write_size]; int fd = SAFE_OPEN(fname, O_RDWR); memset(buf, (intptr_t)arg, write_size); struct flock64 lck = { .l_whence = SEEK_SET, .l_start = 0, .l_len = 1, }; for (i = 0; i < writes_num; ++i) { lck.l_type = F_WRLCK; my_fcntl(fd, F_OFD_SETLKW, &lck); SAFE_LSEEK(fd, 0, SEEK_END); SAFE_WRITE(1, fd, buf, write_size); lck.l_type = F_UNLCK; my_fcntl(fd, F_OFD_SETLKW, &lck); sched_yield(); } SAFE_CLOSE(fd); return NULL; } static void test01(void) { intptr_t i; int k; pthread_t id[thread_cnt]; int res[thread_cnt]; unsigned char buf[write_size]; tst_res(TINFO, "write to a file inside threads with OFD locks"); int fd = SAFE_OPEN(fname, O_CREAT | O_TRUNC | O_RDWR, 0600); memset(res, 0, sizeof(res)); spawn_threads(id, thread_fn_01); wait_threads(id); tst_res(TINFO, "verifying file's data"); SAFE_LSEEK(fd, 0, SEEK_SET); for (i = 0; i < writes_num * thread_cnt; ++i) { SAFE_READ(1, fd, buf, write_size); if (buf[0] >= thread_cnt) { tst_res(TFAIL, "unexpected data read"); return; } ++res[buf[0]]; for (k = 1; k < write_size; ++k) { if (buf[0] != buf[k]) { tst_res(TFAIL, "unexpected data read"); return; } } } for (i = 0; i < thread_cnt; ++i) { if (res[i] != writes_num) { tst_res(TFAIL, "corrupted data found"); return; } } SAFE_CLOSE(fd); tst_res(TPASS, "OFD locks synchronized access between threads"); }
/** * * @param argc * @param argv * @return */ int main(int argc, char** argv) { if (0 != getuid()) { printf("%s", INSUFF_PRIV); exit(EXIT_FAILURE); } start_time = time(NULL); char *host = NULL; int opt = 0; int longIndex = 0; memset(globals.routes, 0, ROUTES_MAX_COUNT); // curl_global_init(CURL_GLOBAL_ALL); // watchdog_stop_flag = false; sheduler_stop_flag = false; pbuffer_stop_flag = false; rotate_stop_flag = false; listen_stop_flag = false; /* Initialize arguments before we get to work. */ char * argument = NULL; argument = "/var/run/arewik.pid"; arguments.pidfile = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.pidfile, argument); argument = "/var/log/arewik"; arguments.logdir = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.logdir, argument); argument = "/var/arewik"; arguments.storagedir = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.storagedir, argument); argument = "/var/arewik/buffers"; arguments.bufferdir = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.bufferdir, argument); argument = "/etc/arewik/arewik.conf"; arguments.configfile = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.configfile, argument); argument = "arewik"; arguments.user = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.user, argument); argument = "arewik"; arguments.group = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.group, argument); argument = "/tmp"; arguments.wdir = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.wdir, argument); argument = DEFAULT_LISTEN_IP; arguments.listen_host = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(arguments.listen_host, argument); arguments.listen_port = DEFAULT_LISTEN_PORT; arguments.verbosity = 0; arguments.foreground = 0; arguments.debuginfo = 0; argument = "custom.log"; globals.custom_logfile_name = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(globals.custom_logfile_name, argument); argument = "debug.log"; globals.debug_logfile_name = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(globals.debug_logfile_name, argument); argument = "connections.log"; globals.connections_logfile_name = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(globals.connections_logfile_name, argument); argument = "access.log"; globals.access_logfile_name = xmalloc(sizeof (char) * strlen(argument) + 1); strcpy(globals.access_logfile_name, argument); globals.maxcon = 4096; // routes max * 64 globals.proxymode = false; //todo globals.routes_cnt = 1; globals.watchdog_interval = WATCHDOG_T; globals.ping_interval = 30; globals.autoreconfigure = false; globals.reconfigure_interval = 60; globals.use_resolver = 0; globals.use_syslog = 0; globals.socktimeout = 10000; globals.epolltimeout = EPOLL_RUN_TIMEOUT; globals.workers = POSSIBLE_FHNDL; sprintf(globals.identline, "%s", ident); // globals.modules[0].id = 0; globals.modules[0].enabled = true; globals.modules[0].name = "plain"; globals.modules[0].process_function = &process_plain; globals.modules[0].init_function = NULL; globals.modules[1].id = 1; globals.modules[1].enabled = false; globals.modules[1].name = "riak"; globals.modules[1].process_function = &process_riak; globals.modules[1].init_function = &init_riak_module; globals.modules[1].close_function = &close_riak; globals.modules[2].id = 2; globals.modules[2].enabled = false; globals.modules[2].name = "esearch"; globals.modules[2].process_function = &process_esearch; globals.modules[2].init_function = &init_esearch_module; globals.modules[2].close_function = &close_esearch; globals.modules[3].id = 3; globals.modules[3].enabled = false; globals.modules[3].name = "webhdfs"; globals.modules[3].process_function = &process_webhdfs; globals.modules[3].init_function = &init_webhdfs_module; globals.modules[3].close_function = &close_webhdfs; CPRESS_FUNCT[0].type = SNAPPY; CPRESS_FUNCT[0].compress_function = &compress_snappy; CPRESS_FUNCT[1].type = GZIP; CPRESS_FUNCT[1].compress_function = &compress_gzip; set_sig_handler(); static const char *optString = "s:D:B:u:g:p:l:c:H:P:vfhd?"; opt = getopt_long(argc, argv, optString, longOpts, &longIndex); while (opt != -1) { switch (opt) { case 'p': if (!is_valid_opt(optarg)) { print_usage(); } arguments.pidfile = xrealloc(arguments.pidfile, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.pidfile, optarg); break; case 'l': if (!is_valid_opt(optarg)) { print_usage(); } arguments.logdir = xrealloc(arguments.pidfile, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.logdir, optarg); break; case 'c': if (!is_valid_opt(optarg)) { print_usage(); } arguments.configfile = xrealloc(arguments.configfile, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.configfile, optarg); break; case 'H': if (!isValidIP(optarg)) { print_usage(); } if (NULL != (host = nslookup(optarg))) { arguments.listen_host = xrealloc(arguments.listen_host, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.listen_host, host); } else { printf("%s\n", hstrerror(h_errno)); exit(EXIT_FAILURE); } break; case 'u': if (!is_valid_opt(optarg)) { print_usage(); } arguments.user = xrealloc(arguments.user, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.user, optarg); break; case 'g': arguments.group = xrealloc(arguments.group, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.group, optarg); break; case 'D': if (!is_valid_opt(optarg)) { print_usage(); } arguments.wdir = xrealloc(arguments.wdir, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.wdir, optarg); break; case 's': if (!is_valid_opt(optarg)) { print_usage(); } arguments.storagedir = xrealloc(arguments.storagedir, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.storagedir, optarg); break; case 'B': if (!is_valid_opt(optarg)) { print_usage(); } arguments.bufferdir = xrealloc(arguments.bufferdir, (sizeof (char) * strlen(optarg) + 1)); strcpy(arguments.bufferdir, optarg); break; case 'P': arguments.listen_port = atoi(optarg); break; case 'v': arguments.verbosity++; break; case 'f': arguments.foreground++; break; case 'h': print_usage(); break; case 'd': arguments.debuginfo++; arguments.verbosity++; break; default: if (!is_valid_opt(optarg)) { print_usage(); } break; } opt = getopt_long(argc, argv, optString, longOpts, &longIndex); } if (false == DirectoryExists(arguments.storagedir)) { printf("Specified storage directory '%s' does not exists\n", arguments.storagedir); printf("Creating new one\n"); if (0 > mkdir(arguments.storagedir, 0755)) { printf("Can not create storage directory - %s\n", strerror(errno)); exit(EXIT_FAILURE); } else { setRightOwner(arguments.storagedir); } } setRightOwner(arguments.storagedir); if (false == DirectoryExists(arguments.bufferdir)) { printf("Specified buffer directory '%s' does not exists\n", arguments.bufferdir); printf("Creating new one\n"); if (0 > mkdir(arguments.bufferdir, 0755)) { printf("Can not create buffer directory - %s\n", strerror(errno)); exit(EXIT_FAILURE); } else { setRightOwner(arguments.bufferdir); } } setRightOwner(arguments.bufferdir); if (true == DirectoryExists(arguments.pidfile)) { printf("Specified pid file '%s' is a directory\n", arguments.pidfile); exit(EXIT_FAILURE); } if (false == DirectoryExists(arguments.wdir)) { printf("Specified working directory '%s' does not exists or not a directory\n", arguments.wdir); exit(EXIT_FAILURE); } if (arguments.foreground == 1) { printf("Running in foreground mode...\n"); setbuf(stdout, 0); setbuf(stdin, 0); setbuf(stderr, 0); } if (arguments.verbosity == 1) { printf("Verbosity enabled\n"); } if (false == FileExists(arguments.configfile)) { printf("Specified file '%s' does not exists\n", arguments.configfile); exit(EXIT_FAILURE); } else if (true == DirectoryExists(arguments.configfile)) { printf("Specified file '%s' is a directory\n", arguments.configfile); exit(EXIT_FAILURE); } else { setRightOwner(arguments.configfile); if (true != hasRightOwner(arguments.configfile)) { printf("The file '%s' has invalid owner/group\nMust be %s:%s\n", arguments.configfile, arguments.user, arguments.group); exit(EXIT_FAILURE); } } if (false == DirectoryExists(arguments.logdir)) { printf("Specified log directory '%s' does not exists\n", arguments.logdir); printf("Creating new one\n"); if (0 > mkdir(arguments.logdir, 0755)) { printf("Can not create log directory - %s\n", strerror(errno)); exit(EXIT_FAILURE); } else { setRightOwner(arguments.logdir); } } setRightOwner(arguments.logdir); if (true != hasRightOwner(arguments.logdir)) { printf("The file '%s' has invalid owner/group\nMust be %s:%s\n", arguments.logdir, arguments.user, arguments.group); exit(EXIT_FAILURE); } glob = readConfig(arguments.configfile); checkPid(); openCustomLog(); openDebugLog(); openConLog(); openAccessLog(); if (!(pwd = getpwnam(arguments.user))) { snprintf(TMP_MSG, MAXLINE, "No such user: %s. Quitting!", arguments.user); writeToCustomLog(TMP_MSG); exit(EXIT_FAILURE); } else my_uid = pwd->pw_uid; if (!(grp = getgrnam(arguments.group))) { snprintf(TMP_MSG, MAXLINE, "No such group: %s. Quitting!", arguments.group); writeToCustomLog(TMP_MSG); exit(EXIT_FAILURE); } else my_gid = grp->gr_gid; if (arguments.foreground == 0) { pid = fork(); if (pid < 0) { snprintf(TMP_MSG, MAXLINE, "%s", "Can not fork! [Invalid PID]"); writeToCustomLog(TMP_MSG); removePid(); exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } // snprintf(TMP_MSG, MAXLINE, "%s", "Forked successfully"); writeToCustomLog(TMP_MSG); /* Change the file mode mask */ umask(027); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { snprintf(TMP_MSG, MAXLINE, "%s", "Can not create child process"); writeToCustomLog(TMP_MSG); /* Log the failure */ removePid(); exit(EXIT_FAILURE); } snprintf(TMP_MSG, MAXLINE, "%s", "Daemonizing"); writeToCustomLog(TMP_MSG); /* Change the current working directory */ if ((chdir(arguments.wdir)) < 0) { snprintf(TMP_MSG, MAXLINE, "%s", "Can not change current directory"); writeToCustomLog(TMP_MSG); /* Log the failure */ exit(EXIT_FAILURE); } snprintf(TMP_MSG, MAXLINE, "%s", "Working directory changed"); writeToCustomLog(TMP_MSG); } savePid(); if ((setgid(my_gid)) < 0) { snprintf(TMP_MSG, MAXLINE, "ERROR: setgid(%d) failed: %s", my_gid, strerror(errno)); writeToCustomLog(TMP_MSG); halt(); } snprintf(TMP_MSG, MAXLINE, "Group ID changed to %d", my_gid); writeToCustomLog(TMP_MSG); if ((setuid(my_uid)) < 0) { snprintf(TMP_MSG, MAXLINE, "ERROR: setuid(%d) failed: %s", my_uid, strerror(errno)); writeToCustomLog(TMP_MSG); halt(); } snprintf(TMP_MSG, MAXLINE, "User ID changed to %d", my_gid); writeToCustomLog(TMP_MSG); if (arguments.foreground == 0) { snprintf(TMP_MSG, MAXLINE, "%s", "Closing descriptors & disabling verbosity.\nEnsure you have set right permissions for your log file.\nWatch your log file for further information\n"); VERBOSE(TMP_MSG); arguments.verbosity = 0; /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } //////////////////////////////////////////////////////////////////////////////// // init_arrays(); init_webhdfs_arrays(); init_active_c_table(); init_descriptors(); scan_connections(); // //////////////////////////////////////////////////////////////////////////////// spawn_threads(); do_listen(); //////////////////////////////////////////////////////////////////////////////// /* This never happens */ return 0; }