예제 #1
0
파일: main.c 프로젝트: BlueCocoa/brainfuck
/*
 * Main entry point of the program.
 *
 * @param argc The amount of arguments given.
 * @param argv The array with arguments.
 */
int main(int argc, char *argv[]) {
	int c;
	int i = 1;
	int option_index = 0;
	
	while (1) {
		option_index = 0;
		c = getopt_long (argc, argv, "he:",
                         long_options, &option_index);
		if (c == -1)
			break;
        
		switch (c) {
            case 0:
                if (long_options[option_index].flag != 0)
                    break;
                break;
            case 'h':
                print_usage();
                return EXIT_SUCCESS;
            case 'e':
                return run_string((char *) optarg);
            case '?':
                print_usage();
                return EXIT_FAILURE;
            default:
                abort();
		}
	}
	if (argc > 1) {
		while (i < argc)
			if (run_file(fopen(argv[i++], "r")) == EXIT_FAILURE)
				fprintf(stderr, "error: failed to read file %s\n", argv[i - 1]);
            else
                printf("\n");
	} else {
		// checks if someone is piping code or just calling it the normal way.
		if (isatty(fileno(stdin))) {
			run_interactive_console();
            printf("\n");
		} else {
			if (run_file(stdin) == EXIT_FAILURE) 
				fprintf(stderr, "error: failed to read from stdin\n");
		}
	}
    
	return EXIT_SUCCESS;
}
예제 #2
0
파일: main.c 프로젝트: ObsidianX/3ds_monty
STATIC int boot_file(const char *device, const char *boot_from, int argc, char **argv, bool return_result) {
    char boot_from_path[PATH_MAX];
    char filename[PATH_MAX];
    char boot_filename[PATH_MAX];

    sprintf(boot_from_path, "%s%s", device, boot_from);
    int init_fd = open(boot_from_path, O_RDONLY);

    int count = read(init_fd, boot_filename, sizeof(filename));

    if (count <= 0) {
        init_console();
        printf("Couldn't read '%s'\nerrno: %d", boot_from_path, errno);
        close(init_fd);
        fatal_error(false);
        return ERR_FILE_NOT_FOUND;
    }

    close(init_fd);

    char *newline = strchr(boot_filename, '\n');
    if (newline) {
        *newline = '\0';
    } else {
        newline = strchr(boot_filename, '\r');
        if (newline) {
            *newline = '\0';
        }
    }

    snprintf(filename, PATH_MAX, "%s%s", device, boot_filename);

    return run_file(filename, argc, argv, return_result);
}
예제 #3
0
  /**
   * Loads the runtime kernel files stored in /runtime.
   * These files consist of the compiled Ruby /kernel code in .rbc files, which
   * are needed to bootstrap the Ruby kernel.
   * This method is called after the VM has completed bootstrapping, and is
   * ready to load Ruby code.
   *
   * @param root The path to the /runtime directory. All kernel loading is
   *             relative to this path.
   */
  void Environment::load_kernel(std::string root) {
    // Check that the index file exists; this tells us which sub-directories to
    // load, and the order in which to load them
    std::string index = root + "/index";
    std::ifstream stream(index.c_str());
    if(!stream) {
      std::string error = "Unable to load kernel index: " + root;
      throw std::runtime_error(error);
    }

    version_ = as<Fixnum>(G(rubinius)->get_const(
          state, state->symbol("RUBY_LIB_VERSION")))->to_native();

    // Load alpha
    run_file(root + "/alpha.rbc");

    while(!stream.eof()) {
      std::string line;

      stream >> line;
      stream.get(); // eat newline

      // skip empty lines
      if(line.empty()) continue;

      load_directory(root + "/" + line);
    }
  }
예제 #4
0
string Process::make_run_file(string config_file, string TGT, string REF, int thread, string metric) {
    // build run script file
    // return: script file name
    char run_buffer[150], report_buffer[150];
    sprintf(run_buffer, "run_%s_%s_%s_%.3d.sh", metric.c_str(), TGT.c_str(), REF.c_str(), thread);   // get the system split
    sprintf(report_buffer, "run_%s_%s_%s_%.3d.report", metric.c_str(), TGT.c_str(), REF.c_str(), thread);   // get the system split

    ofstream run_file(run_buffer);
    if (run_file) {
        run_file << "#$ -S /bin/bash" << endl;
        run_file << "#$ -V" << endl;
        run_file << "#$ -cwd" << endl;
        //run_file << "#$ -m eas" << endl;
        //run_file << "#$ -M [email protected]" << endl;
        run_file << "#$ -l h_vmem=10G" << endl;                 //LA MEMORIA QUE CADA METRICA DEMANI
        //run_file << endl << "DATAPATH=" << Common::DATA_PATH << endl;

        run_file << endl;
        //run_file << "#$ -q short@node115,short@node116,short@node117,short@node315,short@node316" << endl << endl;
        //run_file << endl << ". /home/soft/asiya/ASIYA12.04.PATH" << endl;

        stringstream s_cmd;
        s_cmd << "./Asiya " << config_file << " -serialize " << (thread-1)*TB_FORMAT::chunk + 1 << " -time -g seg -eval single -metric_set metrics_" << metric << " -data_path=" << Common::DATA_PATH << " > " << string(report_buffer);
        string cmd = s_cmd.str();

        if (Config::verbose) fprintf(stderr, "[EXEC] %s\n", cmd.c_str());

        run_file << "echo " << cmd << endl;
        run_file << cmd << endl;

        run_file.close();
    } else { fprintf(stderr, "[ERROR] Could not build config file <%s>\n", run_buffer); exit(1); }

    return string(run_buffer);
}
예제 #5
0
파일: init.c 프로젝트: medici/Scheme-1
void init_global_environment(env_hashtable *env)
{
    init_primitive_procedures(env);
    define_pair_procedures(env);

    /* Preload file */
    run_file(PRELOAD_FILE, env);
}
예제 #6
0
int luax_init()
{
    GStatBuf st;
    const char *config_lua;
    const char *cardpeekrc_lua;

    LUA_STATE= x_lua_begin();

    luaopen_bytes(LUA_STATE);
    luaopen_asn1(LUA_STATE);
    luaopen_bit(LUA_STATE);
    luaopen_card(LUA_STATE);
    luaopen_log(LUA_STATE);
    luaopen_crypto(LUA_STATE);
    luaopen_nodes(LUA_STATE);
    luaopen_iconv(LUA_STATE);
    luaopen_ui(LUA_STATE);

    lua_newtable(LUA_STATE);
    lua_setglobal(LUA_STATE,"cardpeek");

    config_lua = path_config_get_string(PATH_CONFIG_FILE_CONFIG_LUA);
    cardpeekrc_lua = path_config_get_string(PATH_CONFIG_FILE_CARDPEEK_RC);

    if (chdir(path_config_get_string(PATH_CONFIG_FOLDER_CARDPEEK))==-1)
    {
        log_printf(LOG_ERROR,"Could not change to directory '%s'",path_config_get_string(PATH_CONFIG_FOLDER_CARDPEEK));
        return -1;
    }

    if (g_stat(config_lua,&st)==0)
    {
        log_printf(LOG_DEBUG,"Loading configuration script %s",config_lua);
        run_file(LUA_STATE,config_lua);
    }

    if (g_stat(cardpeekrc_lua,&st)==0)
    {
        log_printf(LOG_DEBUG,"Running user configuration script %s",cardpeekrc_lua);
        run_file(LUA_STATE,cardpeekrc_lua);
    }

    return 0;
}
예제 #7
0
void luax_run_script(const char* scriptname)
{
    if (chdir(path_config_get_string(PATH_CONFIG_FOLDER_SCRIPTS))==-1)
    {
        log_printf(LOG_ERROR,"Could not change director to '%s'",path_config_get_string(PATH_CONFIG_FOLDER_SCRIPTS));
        return;
    }
    log_printf(LOG_INFO,"Running script %s (please wait)",scriptname);
    run_file(LUA_STATE,scriptname);
}
예제 #8
0
파일: file_io.c 프로젝트: netspencer/FACT
FACT_t
run_file_soft (func_t *scope)
{
  char   *filename;
  func_t *in;

  in = get_func (scope, "in");
  filename = array_to_string (get_var (scope, "filename"));
  return run_file (in, filename, false);
}
예제 #9
0
  /**
   * Runs rbx from the filesystem. Searches for the Rubinius runtime files
   * according to the algorithm in find_runtime().
   */
  void Environment::run_from_filesystem() {
    int i = 0;
    state->vm()->set_root_stack(reinterpret_cast<uintptr_t>(&i),
                                VM::cStackDepthMax);

    std::string runtime = system_prefix() + RBX_RUNTIME_PATH;

    load_platform_conf(runtime);
    boot_vm();
    start_finalizer();

    load_argv(argc_, argv_);

    start_signals();
    state->vm()->initialize_config();

    load_tool();

    G(rubinius)->set_const(state, "Signature", Integer::from(state, signature_));

    if(LANGUAGE_20_ENABLED(state)) {
      runtime += "/20";
    } else if(LANGUAGE_19_ENABLED(state)) {
      runtime += "/19";
    } else {
      runtime += "/18";
    }
    G(rubinius)->set_const(state, "RUNTIME_PATH", String::create(state,
                           runtime.c_str(), runtime.size()));

    load_kernel(runtime);
    shared->finalizer_handler()->start_thread(state);

    run_file(runtime + "/loader.rbc");

    state->vm()->thread_state()->clear();

    Object* loader = G(rubinius)->get_const(state, state->symbol("Loader"));
    if(loader->nil_p()) {
      rubinius::bug("Unable to find loader");
    }

    OnStack<1> os(state, loader);

    Object* inst = loader->send(state, 0, state->symbol("new"));
    if(inst) {
      OnStack<1> os2(state, inst);

      inst->send(state, 0, state->symbol("main"));
    } else {
      rubinius::bug("Unable to instantiate loader");
    }
  }
예제 #10
0
파일: running.c 프로젝트: cfillion/vifm
/* Tries to run selection displaying error message on file type
 * inconsistency. */
static void
run_selection(FileView *view, int dont_execute)
{
	if(selection_is_consistent(view))
	{
		run_file(view, dont_execute);
	}
	else
	{
		show_error_msg("Selection error",
				"Selection cannot contain files and directories at the same time");
	}
}
예제 #11
0
파일: aestest.c 프로젝트: ajinkya93/OpenBSD
int
main(int argc, char **argv)
{
	int fail = 0, i;

	if (argc < 2)
		errx(1, "usage: aestest [test-vector-file]");

	for (i = 1; i < argc; i++)
		fail += run_file(argv[1]);

	return fail > 0 ? 1 : 0;
}
예제 #12
0
void hectate_fiber_body(FiberManager *my_manager) {
  Context context(my_manager);
  context.setRoot(setup_root());
  my_context = &context;
  
  auto arg = my_manager->getArgs();

  run_file("./init.h6x", context, false);
  
  for (int i = 1; i < arg.argc; i++) {
    if (strcmp(arg.argv[i], "-") == 0) {
      REPL(context);
    }
    else {
      run_file(arg.argv[i], context);
    }
  }

  if (arg.argc <= 1) {
    //have no args
    REPL(context);
  }
  
}
예제 #13
0
파일: main.c 프로젝트: cenan/betik
int main(int argc, char* argv[])
{
#ifdef UNITTESTS
	run_tests(all_unit_tests);
#else // UNITTESTS

	if (argc == 1) {
		printf("usage: %s FILE\n", argv[0]);
		return 2;
	}
	run_file(argv[1]);

#endif // UNITTESTS
	return 0;
}
예제 #14
0
파일: Emma.c 프로젝트: svn2github/coderplay
int main(int argc, char **argv) {

    init_all(argc, argv);


    if (source.type == SOURCE_TYPE_FILE) {
        run_file();

    } else { // SOURCE_TYPE_PROMPT
        run_prompt();
    }

    cleanup();

    return 0;
}
예제 #15
0
파일: main.c 프로젝트: erik/arroyo
int main(int argc, char** argv)
{
  char* filename = NULL;
  int repl_flag=0, help_flag=0;

  struct option long_opts[] = {
    {"help", no_argument, &help_flag, 1},
    {"repl", no_argument, &repl_flag, 1},
    {0,      0,           0,          0}
  };

  int cont = 1;
  while(cont) {
    int opt_index = 0;
    switch(getopt_long(argc, argv, "hr", long_opts, &opt_index)) {
    case -1:
      cont = 0;
      break;

    case 'r':
      repl_flag = 1;
      break;

    case '?':
    case 'h':
      return usage();
    }
  }

  if(optind < argc)
    filename = argv[optind++];

  if((!filename && !repl_flag) || help_flag)
    return usage();

  context* root = context_create();
  root->scope = scope_create(NULL);

  if(filename)
    run_file(filename, root);

  if(repl_flag)
    run_repl(root);

  context_destroy(root);
  return 0;
}
예제 #16
0
  void Environment::load_directory(std::string dir) {
    std::string path = dir + "/load_order.txt";
    std::ifstream stream(path.c_str());
    if(!stream) {
      throw std::runtime_error("Unable to load directory, load_order.txt is missing");
    }

    while(!stream.eof()) {
      std::string line;
      stream >> line;
      stream.get(); // eat newline

      // skip empty lines
      if(line.size() == 0) continue;

      run_file(dir + "/" + line);
    }
  }
예제 #17
0
  void Environment::load_directory(std::string dir) {
    // Read the version-specific load order file.
    std::string path = dir + "/load_order.txt";
    std::ifstream stream(path.c_str());
    if(!stream) {
      std::string msg = "Unable to load directory, " + path + " is missing";
      throw std::runtime_error(msg);
    }

    while(!stream.eof()) {
      std::string line;
      stream >> line;
      stream.get(); // eat newline

      // skip empty lines
      if(line.empty()) continue;

      run_file(dir + "/" + line);
    }
  }
예제 #18
0
파일: main.c 프로젝트: ForeverDev/spyre2
int main(int argc, char** argv) {

	args = 0;
	unsigned int i = 1;
	char outputfn[128];
	char inputfn[128];
	char soloarg[128];

	memset(outputfn, 0, 128);
	memset(inputfn, 0, 128);
	memset(soloarg, 0, 128);

	for (; i < argc; i++) {
		if (!strncmp(argv[i], "-noopt", 6)) {
			args |= MASK_NOOPT;
		} else if (!strncmp(argv[i], "-c", 2)) {
			args |= MASK_COMPILE;
			memcpy(inputfn, argv[++i], 128);
		} else if (!strncmp(argv[i], "-r", 2)) {
			args |= MASK_RUN;
			memcpy(inputfn, argv[++i], 128);
		} else if (!strncmp(argv[i], "-o", 2)) {
			args |= MASK_OUTPUT;
			memcpy(outputfn, argv[++i], 128);
		} else if (!strncmp(argv[i], "-d", 2)) {
			args |= MASK_DUMP;
		} else {
			memcpy(soloarg, argv[i], 128);
		}
	}

	if (args & MASK_COMPILE) {
		compile_file(inputfn, (args & MASK_OUTPUT) ? outputfn : "a.spyb");
    } else if (args & MASK_RUN) {
		run_file(inputfn);
    } else {
		do_file(soloarg);
	}

    return 0;
}
예제 #19
0
파일: splayd.c 프로젝트: JRSteeves/splay
int main(int argc, char *argv[])
{
	int tmp;
	lua_State *L;

	if (argc > 1) {
		if (strcmp(argv[1], "-h") == 0) {
			printf("-h: help\n-d: daemonize\n");
			return 0;
		}
		if (strcmp(argv[1], "-d") == 0) {
			/* no chdir because *.lua will no be found... */
/*            daemon(1, 0);*/
			tmp = daemon(1, 1);
		}
	}

	L = new_lua();
	run_file(L, "splayd.lua");
	printf("End of splayd (C deamon)\n");

	return 0;
}
예제 #20
0
파일: main.c 프로젝트: ObsidianX/3ds_monty
void main_args(int argc, char **argv) {
    if (argc > 1) {
        run_file(argv[1], argc, argv, false);
    }
}
예제 #21
0
파일: main.c 프로젝트: ObsidianX/3ds_monty
void main_netload(int argc, char **argv) {
    bool restart = true;

    while (restart) {
        int ret = run_file("romfs:/netload.py", argc, argv, true);

        if (ret == ERR_PARSE) {
            restart = fatal_error(false);
        } else if (ret == ERR_NETLOAD) {
            restart = false;
        } else {
            mp_obj_dict_t *globals = mp_globals_get();

            qstr filename_qstr = qstr_from_str("monty_filename");
            qstr filetype_qstr = qstr_from_str("monty_filetype");
            qstr cancel_qstr = qstr_from_str("monty_cancel");

            mp_obj_t monty_filename = MP_OBJ_NEW_QSTR(filename_qstr);
            mp_obj_t monty_filetype = MP_OBJ_NEW_QSTR(filetype_qstr);
            mp_obj_t monty_cancel = MP_OBJ_NEW_QSTR(cancel_qstr);

            mp_map_elem_t *filename_item = mp_map_lookup(&globals->map, monty_filename, MP_MAP_LOOKUP);
            mp_map_elem_t *filetype_item = mp_map_lookup(&globals->map, monty_filetype, MP_MAP_LOOKUP);
            mp_map_elem_t *cancel_item = mp_map_lookup(&globals->map, monty_cancel, MP_MAP_LOOKUP);

            if (cancel_item != NULL && mp_obj_is_true(cancel_item->value)) {
                restart = false;
                break;
            }

            const char *filename = "";
            if (filename_item != NULL) {
                filename = mp_obj_str_get_str(filename_item->value);
            }
            char file_path[PATH_MAX];
            sprintf(file_path, "sdmc:/monty3ds/%s", filename);

            int type = TYPE_NONE;
            if (filetype_item != NULL) {
                type = mp_obj_get_int(filetype_item->value);
            }

            switch (type) {
                case TYPE_PY: {
                    ret = run_file(file_path, argc, argv, true);
                    break;
                }
                case TYPE_ZIP: {
                    zipfs_handle_t handle = zipfs_mount(file_path, "zip");
                    zipfs_set_default(handle);

                    ret = boot_file("zip:/", "boot", argc, argv, true);

                    zipfs_unmount(handle);

                    break;
                }
                default:
                    continue;
            }

            if (ret) {
                restart = fatal_error(true);
            }
        }
    }

    mod_citrus_exit_all();
}
예제 #22
0
파일: main.c 프로젝트: netspencer/FACT
void
process_args (int argc, char **argv)
{
  // Very bad function, should be improved later.
  int    arg;
  FACT_t file_open;
  
  var_t  *inter_argc;
  var_t  *inter_argv;
  func_t *scope;

  static int cmdln;

  cmdln = true;
  scope = alloc_func ();
  scope->name = "main";
  init_BIFs (scope);

  file_open = run_file (scope, "/etc/FACT/include/stdlib.ft", true);

  if (file_open.type == ERROR_TYPE)
    errorman_dump (file_open.error);

  for (;;)
    {
      static struct option long_options[] =
	{
	  { "stdin"    , no_argument       , &cmdln , 1   } ,
	  { "no-stdin" , no_argument       , &cmdln , 0   } ,
	  { "shebang"  , required_argument , 0      , 'i' } ,
	  { "file"     , required_argument , 0      , 'f' } ,
	  { 0          , 0                 , 0      , 0   } ,
	};

      int option_index = 0;

      arg = getopt_long (argc, argv, "sdi:f:", long_options, &option_index);

      if (arg == -1)
	break;

      switch (arg)
	{	  
	case 0:
	  if (long_options[option_index].flag != 0)
	    break;
	  break;

	case 's':
	  cmdln = true;
	  break;

	case 'd':
	  cmdln = false;
	  break;

	case 'f':
	  file_open = run_file (scope, optarg, false);

	  if (file_open.type == ERROR_TYPE)
	    errorman_dump (file_open.error);
	  break;

	case 'i':
          // If we're executing a file, parse the remaining arguments into variables.
	  inter_argc = add_var (scope, "argc");
	  mpc_set_si (&(inter_argc->data), argc - 2);

	  inter_argv = add_var (scope, "argv");

	  if (argc - 2 <= 1)
	    mpz_set_ui (inter_argv->array_size, 1);
	  else
	    {
	      mpz_set_ui (inter_argv->array_size, argc - 2);
	      inter_argv->array_up = string_array_to_var (argv + 2, "argv", argc - 2);
	    }

	  file_open = run_file (scope, optarg, true);

	  if (file_open.type == ERROR_TYPE)
	    errorman_dump (file_open.error);
	  exit (0);

	case '?':
	  break;

	default:
	  abort ();
	}
    }

  if (cmdln)
    shell (scope);
}
예제 #23
0
파일: main.c 프로젝트: ForeverDev/spyre2
static void do_file(const char* inputfn) {
	const char* temp = ".tmp_spyre_bytecode.spyb";
	compile_file(inputfn, temp);
	run_file(temp);
	remove(temp);
}
예제 #24
0
gboolean
activate_file (GFile* file, const char* content_type,
               gboolean is_executable, GFile* _file_arg)
{
    char* file_name = g_file_get_basename (file);
    gboolean is_bin = g_str_has_suffix(file_name, ".bin");
    gboolean result = TRUE;

    g_debug ("activate_file: %s", file_name);
    g_free (file_name);
    g_debug ("content_type: %s", content_type);

    if (is_executable &&
        (g_content_type_can_be_executable (content_type) || is_bin))
    {
        g_debug("is_executable && g_content_type_can_be_executable || is_bin");
        //1. an executable text file. or an shell script
        if (g_content_type_is_a (content_type, "text/plain"))
        {
            g_debug("g_content_type_is_a");
            GtkWidget* dialog;
            int response;
            char* file_name;
            char* prompt;
            char* detail;

            file_name = g_file_get_basename (file);
            prompt = g_strdup_printf (_("Do you want to run \"%s\", or display its contents?"), file_name);
            detail = g_strdup_printf (_("\"%s\" is an executable text file."), file_name);
            g_free (file_name);
            //create prompt dialog
            dialog = gtk_message_dialog_new (NULL,
                                             GTK_DIALOG_MODAL,
                                             GTK_MESSAGE_QUESTION,
                                             GTK_BUTTONS_NONE,
                                             NULL);
            g_object_set (dialog, "text", prompt, "secondary-text", detail, NULL);
            g_free (prompt);
            g_free (detail);
            gtk_dialog_add_button (GTK_DIALOG(dialog), _("Run in _Terminal"), RESPONSE_RUN_IN_TERMINAL);
            gtk_dialog_add_button (GTK_DIALOG(dialog), _("_Display"), RESPONSE_DISPLAY);
            gtk_dialog_add_button (GTK_DIALOG(dialog), "_Cancel", GTK_RESPONSE_CANCEL);
            gtk_dialog_add_button (GTK_DIALOG(dialog), _("_Run"), RESPONSE_RUN);
            gtk_dialog_set_default_response (GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL);

            gtk_widget_show (GTK_WIDGET (dialog));

            response = gtk_dialog_run (GTK_DIALOG(dialog));
            gtk_widget_destroy (GTK_WIDGET (dialog));

            g_message("response:%d",response);
            switch (response)
            {
            case RESPONSE_RUN_IN_TERMINAL:
                run_file_in_terminal (file);
                break;
            case RESPONSE_DISPLAY:
                result = display_file (file, content_type);
                break;
            case RESPONSE_RUN:
                run_file (file, NULL);
                break;
            case GTK_RESPONSE_CANCEL:
                break;
            default:
                break;
            }
        }
        //2. an executable binary file
        else
        {
            g_debug("run_file");
            run_file (file, _file_arg);
        }
    }
    //for non-executables just open it.
    else
    {
        g_debug("for non-executables just open it.");
        result = display_file (file, content_type);
    }

    return result;
}
예제 #25
0
파일: jobd.c 프로젝트: lleonini/splay
int main(int argc, char *argv[]) {

	int my_pipe[2], nbytes, tmp;
	int log_fd = 0;
	char read_buffer[1024];

	int sock_fd = 0;
	int portno;
	struct sockaddr_in serv_addr;
	struct hostent *server;

	int total_sent = 0;
	int max_size = 0;
	lua_State *L;

	printf("*** Jobd C starting ***\n");

	if (argc < 2) {
		fprintf(stderr,"usage %s <job_file> [<log_file> [<hostname> <port> [<ref> <session> <max_size> [<exec> [<infos>]]]]]\n", argv[0]);
		exit(1);
	}

	/* File log (no log if file name is "-") */
	if (argc >= 3 && strcmp(argv[2], "-") != 0) {
		if ((log_fd = open(argv[2], O_WRONLY|O_CREAT, 0644)) < 0) {
			perror("open()");
			exit(1);
		}
	}

	/* Network log */
	if (argc >= 5) {

		portno = atoi(argv[4]);
		sock_fd = socket(AF_INET, SOCK_STREAM, 0);
		if (sock_fd < 0) { 
			perror("socket()");
			exit(1);
		}

		server = gethostbyname(argv[3]);

		if (server == NULL) {
			fprintf(stderr, "ERROR, no such host\n");
			exit(1);
		}

		bzero((char *) &serv_addr, sizeof(serv_addr));
		serv_addr.sin_family = AF_INET;
		bcopy((char *)server->h_addr, 
				(char *)&serv_addr.sin_addr.s_addr,
				server->h_length);
		serv_addr.sin_port = htons(portno);

		if (connect(sock_fd, (const struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
			perror("connect()");
			exit(1);
		}
			
		if (argc >= 7) {
			/* ref */
			tmp = write(sock_fd, argv[5], strlen(argv[5]));
			tmp = write(sock_fd, "\n", 1);

			/* session */
			tmp = write(sock_fd, argv[6], strlen(argv[6]));
			tmp = write(sock_fd, "\n", 1);
		}
	}

	if (argc >= 8) {
		max_size = atoi(argv[7]);
		printf("max network log: %d bytes\n", max_size);
	}

	if (pipe(my_pipe) < 0) {
		perror("pipe()");
		exit(1);
	}
	fflush(stdout);

	pid = fork();
	if (pid < 0) {

		perror("fork()");
		exit(1);

	} else if (pid == 0) { /* child */

		close(my_pipe[0]);
		close(1); /* close stdout */
		close(2); /* close stderr */
		tmp = dup(my_pipe[1]); /* new stdout */
		tmp = dup(my_pipe[1]); /* new stderr */

		if (argc >= 9 && strcmp(argv[8], "exec") == 0) {

			printf("SPLAYD SCRIPT EXEC\n");
			chmod(argv[1], S_IRUSR|S_IXUSR|S_IWUSR);
			if (argc >= 10) {
				execl(argv[1], argv[1], argv[3], argv[4], argv[9], (char *) NULL);
			} else {
				execl(argv[1], argv[1], argv[3], argv[4], (char *) NULL);
			}

		} else {
			/**** Lua application start here !!! ****/
			L = new_lua();

			lua_pushstring(L, argv[1]);
			lua_setglobal(L, "job_file");

			printf("SPLAYD LUA EXEC\n");
			run_file(L, "jobd.lua");
			printf("SPLAYD LUA END\n");
		}

		exit(0);

	} else if (pid > 0) { /* parent */

		signal(SIGTERM, sighandler_term);

		close(my_pipe[1]);
		close(0); /* close stdin */
		tmp = dup(my_pipe[0]); /* new stdin */

		while (1) {
			bzero(read_buffer, sizeof(read_buffer));
			nbytes = read(my_pipe[0], read_buffer, sizeof(read_buffer));
			if (nbytes == 0) { /* 0 only if EOF (child is dead) */
				if (argc >= 3) {
					close(log_fd);
				}
				if (argc >= 5) {
					close(sock_fd);
				}
				exit(0);
			}
			if (nbytes > 0) {
				total_sent += nbytes;

				/* NOTE: in production comment next line */
				tmp = write(1, read_buffer, nbytes);

				if (log_fd > 0) {
					nbytes = write(log_fd, read_buffer, nbytes);
					if (nbytes < 0) {
						perror("file write()");
					}
				}

				if (sock_fd > 0 && (max_size == 0 || total_sent < max_size)) {
					nbytes = write(sock_fd, read_buffer, nbytes);
					if (nbytes < 0) {
						/* TODO eventually try reconnecting... */
						perror("socket write()");
						close(sock_fd);
						sock_fd = 0;
					}
				} else {
					close(sock_fd);
					sock_fd = 0;
				}
			}
		}
	}

	return 0;
}
예제 #26
0
/**
 * @name	core_init_js
 * @brief	initilizes js options and runs the packed javascript game code
 * @param	uri - (const char*)  ____
 * @param	version - (const char*) ____
 * @retval	bool - (true | false) depending on whether running the javascript source was successful
 */
bool core_init_js(const char *uri, const char *version) {
	init_js(uri, version);
	return run_file("native.js");
}