/** * Main execution of the program. Function calls * to load data from file, calculation of maximum flow * and to save result answer to a file */ int main(int argc, char *argv[]) { /* Corrects terminal output buffer */ setvbuf(stderr, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); /* Parse main arguments */ char input[ARGS_BUFFER_SIZE], output[ARGS_BUFFER_SIZE]; arg_parser(argc, argv, input, output); #ifdef MYDEBUG printf("input: %s output: %s\n", input, output); #endif /* Import input file */ FILE *inpfile = openfile(input, READ_MODE); /* Loads data from file */ Champ champ; load(inpfile, &champ); closefile(inpfile); /* output file that will store the results */ FILE *outfile = openfile(output, WRITE_MODE); /* Calculate the maximum flow on the graph */ maximum_flow(&champ, outfile); closefile(outfile); return EXIT_SUCCESS; }
int main(int argc, char **argv) { enum arg_index ret; int fd; while ((ret = arg_parser(argc, argv, args)) != ARG_DONE) { switch (ret) { case ARG_help: display_help_text(argv[0], arg_str, usage_str, arg_desc_str, args); return 0; case ARG_version: printf("%s", version_text); return 0; case ARG_EXTRA: fd = open(argarg, O_RDONLY | O_CREAT, 0777); if (fd == -1) { perror(argarg); return 0; } close(fd); break; case ARG_ERR: default: return 0; } } return 0; }
int main(int argc, char **argv) { enum arg_index ret; while ((ret = arg_parser(argc, argv, args)) != ARG_DONE) { switch (ret) { case ARG_help: display_help_text(argv[0], arg_str, usage_str, arg_desc_str, args); return 0; case ARG_version: printf("%s", version_text); return 0; case ARG_EXTRA: ret = mkdir(argarg, 0777); if (ret) { perror(argarg); return 0; } break; case ARG_ERR: default: return 0; } } return 0; }
MStatus mengerCmd::doIt(const MArgList &args) { MSyntax syntax; syntax.addFlag(FLAG_SIZE, FLAG_SIZE_LONG, MSyntax::kDouble); syntax.addFlag(FLAG_ITER, FLAG_ITER_LONG, MSyntax::kUnsigned); MStatus stat = MStatus::kSuccess; MArgParser arg_parser(syntax, args, &stat); if (stat != MStatus::kSuccess) return stat; double size = 1.0f; stat = arg_parser.getFlagArgument(FLAG_SIZE, 0, size); unsigned int iterations = 3; stat = arg_parser.getFlagArgument(FLAG_ITER, 0, iterations); cube c; c.start.x = c.start.y = c.start.z = (float) -size; c.end = c.start * -1; std::vector<cube> cubes; dice_err::val dice_status = dice(c, iterations, cubes); if (dice_status == dice_err::success) { MGlobal::displayInfo("A Menger Sponge was created."); MString name; makeCubes(cubes, name, &stat); setResult(name); } else { MGlobal::displayError("A Menger Sponge could not be computed."); switch (dice_status) { case dice_err::invalid_param_err: MGlobal::displayError("dice was called with wrong arguments."); break; case dice_err::bounds_err: MGlobal::displayError("dice was called with erronous bounds."); break; case dice_err::memory_err: MGlobal::displayError("dice had an memory error."); break; case dice_err::success: /* Stop warnings. */ break; } } return stat; }
void parse_args(int argc, char **argv, struct arg_state *s) { enum arg_list ret; while ((ret = arg_parser(argc, argv, cmips_args)) != ARG_DONE) { switch (ret) { case ARG_help: display_help_text(argv[0], cmips_args); exit(0); break; case ARG_version: printf("%s", version_text); exit(0); break; case ARG_quiet: s->quiet = 1; break; case ARG_run: s->run = 1; break; case ARG_noinput: s->noinput = 1; break; case ARG_script: s->cmd_script = argarg; break; case ARG_EXTRA: if (emulator_load_from_file(&cmips_emu, argarg)) { printf("Error assembling file.\n"); s->quiet = 1; s->noinput = 1; return ; } break; default: case ARG_ERR: /* Error message already printed by getopt_long() */ exit(0); break; } } return ; }
int main(int argc, char **argv) { bool show_all = false; int dirs = 0, i; const char *dirarray[DIRMAX] = { NULL }; enum arg_index ret; while ((ret = arg_parser(argc, argv, ls_args)) != ARG_DONE) { switch (ret) { case ARG_help: display_help_text(argv[0], usage_str, desc_str, ls_args); return 0; case ARG_all: show_all = true; break; case ARG_EXTRA: if (dirs < sizeof(dirarray)) { dirarray[dirs++] = argarg; } else { fprintf(stderr, "%s: To many directories given to ls\n", argv[0]); return 1; } break; default: return 0; } } if (dirs == 0) { dirarray[dirs++] = "./"; } for (i = 0; i < dirs; i++) { DIR *directory = opendir(dirarray[i]); if (directory == NULL) { perror(*argv); return 1; } list_items(directory, show_all); printf("\n"); } }
token get_token() { token next; char c; std::ostringstream buf; if (input.eof()) { next.kind = token::TOK_EOF; } else { c = getchar(input); switch (c) { case '{': case '}': case '@': next.kind = token::TOK_LITERAL; buf << c; c = getchar(input); break; case '\\': { c = getchar(input); if (c == '\\') { next.kind = token::TOK_TEXT; buf << "\n"; c = getchar(input); break; } else if (c == '-') { getchar(input); return get_token(); } else if (c == '&' || c == ',' || c == '>' || c == '#' || c == '%' || c == '^' || c == '=') { next.kind = token::TOK_TEXT; buf << c; c = getchar(input); break; } else if (c == '{' || c == '}') { next.kind = token::TOK_LITERAL; buf << c; break; } else { next.kind = token::TOK_DIRECTIVE; } do { buf << c; c = getchar(input); } while (! input.eof() && (std::isalnum(c) || c == '_')); if (! input.eof() && c == '[') { std::ostringstream arg; c = arg_parser(input, arg, '[', ']'); next.bracket_arg = arg.str(); } if (! input.eof() && c == '|') { std::ostringstream arg; c = arg_parser(input, arg, '|', '|'); next.brace_args.push_back(arg.str()); } char save = c; size_t linenum_save = linenum; std::streamoff pos = skip_whitespace(input, c); while (! input.eof() && c == '{') { std::ostringstream arg; c = arg_parser(input, arg, '{', '}'); next.brace_args.push_back(arg.str()); save = c; linenum_save = linenum; pos = skip_whitespace(input, c); } next.text = buf.str(); if (next.text != "pnum") { input.seekg(pos, std::ios::beg); c = save; linenum = linenum_save; } break; } case '$': next.kind = token::TOK_EQUATION; do { buf << c; c = getchar(input); } while (! input.eof() && c != '$' && c != '\n'); break; case '%': next.kind = token::TOK_COMMENT; do { buf << c; c = getchar(input); } while (! input.eof() && c != '\n'); #if 0 if (c == '\n') { buf << c; c = getchar(input); } #endif break; case '&': if (state == STATE_TABLE) { next.kind = token::TOK_UNBREAKABLE_SPACE; buf << "\n"; buf << "@tab"; c = getchar(input); break; } // else, fall through... case '~': if (c == '~' && state != STATE_LITERAL) { next.kind = token::TOK_UNBREAKABLE_SPACE; buf << c; c = getchar(input); break; } // else, fall through... default: next.kind = token::TOK_TEXT; do { assert(c != '\0'); buf << c; c = getchar(input); } while (! input.eof() && c != '$' && c != '%' && c != '&' && c != '@' && c != '\\' && c != '{' && c != '}' && c != '~'); break; } if (! input.eof()) { if (c == '\n') linenum--; input.putback(c); } next.text = buf.str(); next.linenum = linenum; if (next.text == "begin") { if (next.brace_args.front() == "codeblock") state = STATE_LITERAL; else if (next.brace_args.front() == "tokentable" || next.brace_args.front() == "floattable") state = STATE_TABLE; } else if (next.text == "end") { if (next.brace_args.front() == "codeblock") state = STATE_NORMAL; else if (next.brace_args.front() == "tokentable" || next.brace_args.front() == "floattable") state = STATE_NORMAL; } } return next; }
int main(int argc, char **argv) { const char *iface = NULL; enum arg_index ret; struct ifreq ifreq; char *cmd = NULL, *cmd_arg = NULL; prog = argv[0]; while ((ret = arg_parser(argc, argv, args)) != ARG_DONE) { switch (ret) { case ARG_help: display_help_text(argv[0], arg_str, usage_str, arg_desc_str, args); return 0; case ARG_version: printf("%s", version_text); return 0; case ARG_EXTRA: if (!iface) { iface = argarg; } else if (!cmd) { cmd = argarg; } else if (!cmd_arg) { cmd_arg = argarg; } else { printf("%s: Too many arguments\n", argv[0]); return 0; } break; case ARG_ERR: default: return 0; } } netdev_fd = open(NETDEV, O_RDONLY); if (netdev_fd == -1) { perror(NETDEV); return 1; } if (iface) { strncpy(ifreq.ifr_name, iface, IFNAMSIZ); ret = ioctl(netdev_fd, SIOCGIFINDEX, &ifreq); if (ifreq.ifr_index == -1 || ret) { printf("Unable to access %s: %s\n", iface, strerror(errno)); return 1; } if (cmd) execute_cmd(&ifreq, cmd, cmd_arg); else display_iface(&ifreq); } else { int i = 0; int err = 0; int found = 0; for (; !err; i++) { ifreq.ifr_index = i; err = ioctl(netdev_fd, SIOCGIFNAME, &ifreq); if (!err) { found = 1; display_iface(&ifreq); } } if (!found) printf("No Network Interfaces found\n"); } close(netdev_fd); return 0; }
int main(int argc, char **argv) { try { // First thing, set up logging. Logger::Init(argv[0]); // We'll keep the scanner threads in this vector so we can join() them later. std::vector<std::thread> scanner_threads; // Instantiate classes for file and directory inclusion/exclusion management. TypeManager type_manager; DirInclusionManager dir_inclusion_manager; // Instantiate the argument parser. ArgParse arg_parser(type_manager); // Parse command-line options and args. arg_parser.Parse(argc, argv); dir_inclusion_manager.AddExclusions(arg_parser.m_excludes); type_manager.CompileTypeTables(); dir_inclusion_manager.CompileExclusionTables(); LOG(INFO) << "Num scanner jobs: " << arg_parser.m_jobs; // Create the Globber->FileScanner queue. sync_queue<FileID> files_to_scan_queue; // Create the FileScanner->OutputTask queue. sync_queue<MatchList> match_queue; // Set up the globber. Globber globber(arg_parser.m_paths, type_manager, dir_inclusion_manager, arg_parser.m_recurse, arg_parser.m_follow_symlinks, arg_parser.m_dirjobs, files_to_scan_queue); // Set up the output task object. OutputTask output_task(arg_parser.m_color, arg_parser.m_nocolor, arg_parser.m_column, match_queue); // Create the FileScanner object. std::unique_ptr<FileScanner> file_scanner(FileScanner::Create(files_to_scan_queue, match_queue, arg_parser.m_pattern, arg_parser.m_ignore_case, arg_parser.m_word_regexp, arg_parser.m_pattern_is_literal)); // Start the output task thread. std::thread output_task_thread {&OutputTask::Run, &output_task}; // Start the scanner threads. for(int t=0; t<arg_parser.m_jobs; ++t) { std::thread fst {&FileScanner::Run, file_scanner.get(), t}; scanner_threads.push_back(std::move(fst)); } // Start the globber threads last. // We do this last because the globber is the ultimate source for the work queue; all other threads will be // waiting for it to start sending data to the Globber->FileScanner queue. If we started it // first, the globbing would start immediately, and it would take longer to get the scanner and output // threads created and started, and ultimately slow down startup. // Note that we just call globber.Run() here. It blocks, spawning and managing its own threads until the directory // tree traversal is complete. globber.Run(); // Close the Globber->FileScanner queue. files_to_scan_queue.close(); // Wait for all scanner threads to complete. for (auto& scanner_thread_ref : scanner_threads) { scanner_thread_ref.join(); } // All scanner threads completed. // Close the FileScanner->OutputTask queue. match_queue.close(); // Wait for the output thread to complete. output_task_thread.join(); auto total_matched_lines = output_task.GetTotalMatchedLines(); if(total_matched_lines == 0) { // No matches, return a grep-compatible 1. return 1; } else { // Found some matches, return success. return 0; } } catch(const FileScannerException &e) { ERROR() << "Error during regex parsing: " << e.what(); return 255; } catch(const ArgParseException &e) { ERROR() << "Error during arg parsing: " << e.what(); return 255; } catch(const std::runtime_error &e) { ERROR() << "std::runtime_error exception: " << e.what(); return 255; } catch(...) { // We shouldn't need this catch(...), but Cygwin seems to not properly call the default // terminate handler (which should be abort()) if we let an exception escape main(), but will simply return // without an error code. I ran into this when trying to instantiate std::locale with locale=="" in ArgParse, // and before I had the std::runtime_error catch clause above. ERROR() << "Unknown exception occurred."; std::abort(); } }
int main(int argc, char** argv) { //Setting the signals to trigger the cleanup function signal(SIGTERM, Cleanup); signal(SIGINT, Cleanup); //Define and process command line arguments std::string log_dir; std::string gateway_socket_url; bool gateway_socket_url_defined; bool nanomsg; ArgParse::ArgParser arg_parser("KSync Server - Server side of a Client-Server synchonization system using rsync."); KSync::Utilities::set_up_common_arguments_and_defaults(arg_parser, log_dir, gateway_socket_url, gateway_socket_url_defined, nanomsg); int status; if((status = arg_parser.ParseArgs(argc, argv)) < 0) { printf("Problem parsing arguments\n"); arg_parser.PrintHelp(); return -1; } if(arg_parser.HelpPrinted()) { return 0; } if (log_dir == "") { if(KSync::Utilities::get_user_ksync_dir(log_dir) < 0) { printf("There was a problem getting the ksync user directory!\n"); return -2; } } //Initialize logging: std::unique_ptr<g3::LogWorker> logworker; KSync::InitializeLogger(logworker, true, "KSync Server", log_dir); //Get gateway URL if (KSync::Utilities::GetGatewaySocketURL(gateway_socket_url, gateway_socket_url_defined) < 0) { LOGF(SEVERE, "There was a problem getting the gateway socket URL!"); return -2; } LOGF(INFO, "Using the following socket url: %s", gateway_socket_url.c_str()); //Initialize communication system std::shared_ptr<KSync::Comm::CommSystemInterface> comm_system; if (KSync::Utilities::GetCommSystem(comm_system, nanomsg) < 0) { LOGF(SEVERE, "There was a problem initializing the comm system!"); return -2; } //Initialize command system std::shared_ptr<KSync::Commanding::SystemInterface> command_system(new KSync::Commanding::PSCommandSystem()); //Initialize Gateway Thread socket std::shared_ptr<KSync::Comm::CommSystemSocket> gateway_thread_socket; if (comm_system->Create_Pair_Socket(gateway_thread_socket, 10) < 0) { LOGF(SEVERE, "There was a problem creating the gateway thread socket!"); return -3; } std::string gateway_thread_socket_url; if(KSync::Utilities::get_default_gateway_thread_url(gateway_thread_socket_url) < 0) { LOGF(SEVERE, "There was a problem getting the default gateway thread socket url!"); return -4; } if(gateway_thread_socket->Bind(gateway_thread_socket_url) < 0) { LOGF(SEVERE, "There was a problem binding the gateway thread socket!"); return -5; } //Launch Gateway Thread std::thread gateway(KSync::Server::gateway_thread, comm_system, gateway_thread_socket_url, gateway_socket_url); //Acknowledge connection std::shared_ptr<KSync::Comm::CommObject> herald_obj; status = gateway_thread_socket->Recv(herald_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(SEVERE, "Didn't receive connect herald!"); return -6; } else if ((status == KSync::Comm::CommSystemSocket::Timeout)|| (status == KSync::Comm::CommSystemSocket::EmptyMessage)) { LOGF(SEVERE, "Herald retreive timed out!!!"); return -7; } else { if(herald_obj->GetType() == KSync::Comm::SocketConnectHerald::Type) { KSync::Comm::SocketConnectAcknowledge ack; std::shared_ptr<KSync::Comm::CommObject> ack_obj = ack.GetCommObject(); status = gateway_thread_socket->Send(ack_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(SEVERE, "Couldn't send Acknowledgement!"); return -7; } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(SEVERE, "Retreival of Ack timed out!!"); return -8; } } else { LOGF(SEVERE, "Didn't get a herald type (%i)!!\n", herald_obj->GetType()); return -8; } } KSync::Comm::ClientCommunicatorList client_communicators; while(!finished) { //Check gateway thread std::shared_ptr<KSync::Comm::CommObject> recv_obj; status = gateway_thread_socket->Recv(recv_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(SEVERE,"There was a problem checking the gateway thread socket!"); return -9; } else if (status == KSync::Comm::CommSystemSocket::Timeout) { } else if (status == KSync::Comm::CommSystemSocket::EmptyMessage) { } else { // Handle connection request!! if(recv_obj->GetType() == KSync::Comm::GatewaySocketInitializationRequest::Type) { LOGF(INFO, "Received a connection request!"); std::shared_ptr<KSync::Comm::GatewaySocketInitializationRequest> request; KSync::Comm::CommCreator(request, recv_obj); LOGF(INFO, "Received client id: (%lu)\n",request->GetClientId()); std::shared_ptr<KSync::Comm::ClientCommunicator> client_communicator = client_communicators.find_first_if(request->GetClientId()); if(client_communicator == nullptr) { LOGF(INFO, "Generating new client socket!"); //Don't have a client with that ID yet! Handle creation of new socket client_communicator.reset(new KSync::Comm::ClientCommunicator(comm_system, request->GetClientId(), true)); //std::string new_socket_url; //if(KSync::Utilities::get_client_socket_url(new_socket_url, request->GetClientId()) < 0) { // LOGF(SEVERE, "Error! Couldn't get the client socket url!"); // return -10; //} //std::shared_ptr<KSync::Comm::CommSystemSocket> client_socket; //if (comm_system->Create_Pair_Socket(client_socket) < 0) { // LOGF(SEVERE, "There was a problem creating the gateway thread socket!"); // return -10; //} //if (client_socket->SetRecvTimeout(1000) < 0) { // LOGF(SEVERE, "There was a problem setting the recv timeout!"); // return -10; //} //if(client_socket->Bind(new_socket_url) < 0) { // LOGF(SEVERE, "There was a problem binding the gateway thread socket!"); // return -10; //} client_communicators.push_front(*client_communicator); KSync::Comm::ClientSocketCreation socket_message; socket_message.SetClientUrl(new_socket_url); socket_message.SetBroadcastUrl(broadcast_url); std::shared_ptr<KSync::Comm::CommObject> socket_message_obj = socket_message.GetCommObject(); LOGF(INFO, "Sending new client socket address!"); status = gateway_thread_socket->Send(socket_message_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(SEVERE, "Couldn't send response!"); return -11; } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(SEVERE, "Sending response timed out!!"); return -12; } } else { //We have a client with that ID! LOGF(WARNING, "We already have a client with ID (%lu)!\n", request->GetClientId()); KSync::Comm::GatewaySocketInitializationChangeId response; std::shared_ptr<KSync::Comm::CommObject> resp_obj = response.GetCommObject(); status = gateway_thread_socket->Send(resp_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(SEVERE, "There was a problem sending a response to the gateway thread socket!"); return -11; } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(SEVERE, "Sending response timedout!!"); return -12; } } } else { LOGF(SEVERE, "Unsupported message from gateway thread! (%i) (%s)\n", recv_obj->GetType(), KSync::Comm::GetTypeName(recv_obj->GetType())); return -11; } } //Check client sockets for(auto client_socket_it = client_sockets.begin(); client_socket_it != client_sockets.end(); ++client_socket_it) { //Check for incoming messages recv_obj = 0; std::shared_ptr<KSync::Comm::CommSystemSocket> client_socket = client_socket_it->second; status = client_socket->Recv(recv_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(WARNING, "There was a problem receiving a message from a client socket!"); } else if ((status == KSync::Comm::CommSystemSocket::Timeout)||(status == KSync::Comm::CommSystemSocket::EmptyMessage)) { } else { if(recv_obj->GetType() == KSync::Comm::CommString::Type) { std::shared_ptr<KSync::Comm::CommString> message; KSync::Comm::CommCreator(message, recv_obj); LOGF(INFO, "Got message (%s)\n", message->c_str()); std::shared_ptr<KSync::Comm::CommObject> send_obj = message->GetCommObject(); status = client_socket->Send(send_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(WARNING, "There was a problem sending a message on a client socket!"); } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(WARNING, "Sending a message on a client socket timed out!"); } } else if (recv_obj->GetType() == KSync::Comm::ShutdownRequest::Type) { finished = true; KSync::Comm::ShutdownAck shutdown_ack; std::shared_ptr<KSync::Comm::CommObject> shutdown_obj = shutdown_ack.GetCommObject(); status = client_socket->Send(shutdown_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(WARNING, "There was a problem sending the shutdown ack"); } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(WARNING, "There was a timeout sending the shutdown ack"); } } else if (recv_obj->GetType() == KSync::Comm::ExecuteCommand::Type) { std::shared_ptr<KSync::Comm::ExecuteCommand> exec_com; KSync::Comm::CommCreator(exec_com, recv_obj); LOGF(INFO, "Received command (%s)\n", exec_com->c_str()); std::shared_ptr<KSync::Commanding::ExecutionContext> command_context = command_system->GetExecutionContext(); command_context->LaunchCommand(exec_com->c_str()); std::string std_out; std::string std_err; command_context->GetOutput(std_out, std_err); KSync::Comm::CommandOutput com_out; com_out.SetStdout(std_out); com_out.SetStderr(std_err); com_out.SetReturnCode(command_context->GetReturnCode()); std::shared_ptr<KSync::Comm::CommObject> test_resp = com_out.GetCommObject(); status = client_socket->Send(test_resp); if(status != KSync::Comm::CommSystemSocket::Success) { LOGF(WARNING, "There was a problem sending the test reponse!"); } } } } } // Shutting down // Broadcast shutdown message KSync::Comm::ServerShuttingDown shutdown_message; std::shared_ptr<KSync::Comm::CommObject> shutdown_obj = shutdown_message.GetCommObject(); status = broadcast_socket->Send(shutdown_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(WARNING, "There was a problem sending the shutdown message!"); } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(WARNING, "There was a timeout sending the shutdown message!"); } else { LOGF(WARNING, "Shutdown sent!"); } // Shutdown gateway thread status = gateway_thread_socket->Send(shutdown_obj); if(status == KSync::Comm::CommSystemSocket::Other) { LOGF(WARNING, "There was a problem closing down the gateway thread!"); } else if (status == KSync::Comm::CommSystemSocket::Timeout) { LOGF(WARNING, "There was a timeout closing down the gateway thread!"); } //Join gateway thread gateway.join(); return 0; }