Пример #1
0
int main(int argc, char **argv) {
    int r;

    setlocale(LC_ALL, "");

    parse_opts(argc, argv);

    aug = aug_init(root, loadpath, flags|AUG_NO_ERR_CLOSE);
    if (aug == NULL || aug_error(aug) != AUG_NOERROR) {
        fprintf(stderr, "Failed to initialize Augeas\n");
        if (aug != NULL)
            print_aug_error();
        exit(EXIT_FAILURE);
    }
    add_transforms(transforms, transformslen);
    if (print_version) {
        print_version_info();
        return EXIT_SUCCESS;
    }
    readline_init();
    if (optind < argc) {
        // Accept one command from the command line
        r = run_args(argc - optind, argv+optind);
    } else {
        r = main_loop();
    }
    if (history_file != NULL)
        write_history(history_file);

    return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Пример #2
0
int main (int argc, 
          char *argv[]) 
{
  TIDC_INSTANCE *tidc;
  int conn = 0;
  int rc;
  gss_ctx_id_t gssctx;
  struct cmdline_args opts;

  /* parse the command line*/
  /* set defaults */
  opts.server=NULL;
  opts.rp_realm=NULL;
  opts.target_realm=NULL;
  opts.community=NULL;
  opts.port=TID_PORT;

  argp_parse(&argp, argc, argv, 0, 0, &opts);
  /* TBD -- validity checking, dealing with quotes, etc. */

  print_version_info();

  /* Use standalone logging */
  tr_log_open();

  /* set logging levels */
  talloc_set_log_stderr();
  tr_log_threshold(LOG_CRIT);
  tr_console_threshold(LOG_DEBUG);

  printf("TIDC Client:\nServer = %s, rp_realm = %s, target_realm = %s, community = %s, port = %i\n", opts.server, opts.rp_realm, opts.target_realm, opts.community, opts.port);
 
  /* Create a TID client instance & the client DH */
  tidc = tidc_create();
  if (NULL == (tidc->client_dh = tr_create_dh_params(NULL, 0))) {
    printf("Error creating client DH params.\n");
    return 1;
  }

  /* Set-up TID connection */
  if (-1 == (conn = tidc_open_connection(tidc, opts.server, opts.port, &gssctx))) {
    /* Handle error */
    printf("Error in tidc_open_connection.\n");
    return 1;
  };

  /* Send a TID request */
  if (0 > (rc = tidc_send_request(tidc, conn, gssctx, opts.rp_realm, opts.target_realm, opts.community, 
				  &tidc_resp_handler, NULL))) {
    /* Handle error */
    printf("Error in tidc_send_request, rc = %d.\n", rc);
    return 1;
  }
    
  /* Clean-up the TID client instance, and exit */
  tidc_destroy(tidc);

  return 0;
}
/* --------------------------------------------------------------------------*/
int player_start(play_control_t *ctrl_p, unsigned long  priv)
{
    int ret;
    int pid = -1;
    play_para_t *p_para;
    //char stb_source[32];

    update_loglevel_setting();
    print_version_info();
    log_print("[player_start:enter]p=%p black=%d\n", ctrl_p, get_black_policy());

    if (ctrl_p == NULL) {
        return PLAYER_EMPTY_P;
    }

    /*keep last frame displaying --default*/
    set_black_policy(0);
    /* if not set keep last frame, or change file playback, clear display last frame */
    if (!ctrl_p->displast_frame) {
        set_black_policy(1);
    } else if (!check_file_same(ctrl_p->file_name)) {
        set_black_policy(1);
    }

    pid = player_request_pid();
    if (pid < 0) {
        return PLAYER_NOT_VALID_PID;
    }

    p_para = MALLOC(sizeof(play_para_t));
    if (p_para == NULL) {
        return PLAYER_NOMEM;
    }

    MEMSET(p_para, 0, sizeof(play_para_t));

    /* init time_point to a invalid value */
    p_para->playctrl_info.time_point = -1;

    player_init_pid_data(pid, p_para);

    message_pool_init(p_para);

    p_para->start_param = ctrl_p;
    p_para->player_id = pid;
    p_para->extern_priv = priv;
    log_debug1("[player_start]player_para=%p,start_param=%p pid=%d\n", p_para, p_para->start_param, pid);

    ret = player_thread_create(p_para) ;
    if (ret != PLAYER_SUCCESS) {
        FREE(p_para);
        player_release_pid(pid);
        return PLAYER_CAN_NOT_CREAT_THREADS;
    }
    log_print("[player_start:exit]pid = %d \n", pid);

    return pid;
}
Пример #4
0
static int pack_ver_info(FILE *fp_w, uint32 offset, char *desc)
{
    version_info ver_t;
    FILE *fp_r;
    int i;

    memset((char *)&ver_t, 0, sizeof(version_info));

    if (strlen(desc) >= DESCLEN)
    {
        printf("The upk_desc is too long\n");
        return(-1);
    }
    strncpy((char *)ver_t.upk_desc, desc, DESCLEN-1);
    strncpy((char *)ver_t.pack_id, (char *)PACKAGE_ID, NAMELEN-1);
    strncpy((char *)ver_t.os_ver,  "0.00", VERLEN-1);
    strncpy((char *)ver_t.app_ver, "0.00", VERLEN-1);

    if ((fp_r = fopen(KERNEL_VER_FILE, "rb")) == NULL)
    {
        printf("Can't open OS version file: %s\n", KERNEL_VER_FILE);
        return(-1);
    }
    for (i = 0; i < sizeof(ver_t.os_ver); i++)
    {
        if (feof(fp_r)) break;
        ver_t.os_ver[i] = fgetc(fp_r);
        if ((ver_t.os_ver[i]==0x0d) || (ver_t.os_ver[i]==0x0a))
            ver_t.os_ver[i] = '\0';
    }
    fclose(fp_r);

    if ((fp_r = fopen(ROOTFS_VER_FILE, "rb")) == NULL)
    {
        printf("Can't open App version file: %s\n", ROOTFS_VER_FILE);
        return(-1);
    }
    for (i = 0; i < sizeof(ver_t.app_ver); i++)
    {
        if (feof(fp_r)) break;
        ver_t.app_ver[i] = fgetc(fp_r);
        if ((ver_t.app_ver[i]==0x0d) || (ver_t.app_ver[i]==0x0a))
            ver_t.app_ver[i] = '\0';
    }
    fclose(fp_r);

    fseek(fp_w, 0, SEEK_SET);
    if (fwrite((uint8 *)&ver_t, sizeof(version_info), 1, fp_w) != 1)
    {
        printf("can not write the version struct into package\n");
        return(-1);
    }

    print_version_info(&ver_t);

    return(0);
}
  /**
   * If you have extra command line parameters, you may use this method to start CPUnit
   * after you have done your own. You should use {@link #get_cmd_line_parser()} to obtain
   * a parser which is already set up to accept the CPUnit specific command line parameters,
   * and then use CmdLineParser.add_legal to specify the arguments you expect in addition.
   * 
   * @param parser A parser contaiing the command line arguments, excluding the program name.
   *               I.e. from main(int& argc,char** args), the parser would be called as
   *               {@link CmdLineParser#parse(const int, const char**) parser.parse(arcg-1,args+1)}.
   * @return 0 if all tests succeed, and >0 elsewise.
  */
  int main(const CmdLineParser &parser) {

    AutoDisposer ad;
    try {
      CPUNIT_ITRACE("EntryPoint - Actual arguments:"<<parser.to_string());

      std::vector<std::string> patterns = parser.program_input();
      if (patterns.size() == 0) { 
	patterns.push_back("*");
      }
      
      if(parser.has_one_of("-h --help")) {
	usage();
	return 0;
      }
      if(parser.has_one_of("-L --list")) {
	list_tests(patterns);
	return 0;
      }
      if(parser.has_one_of("-V --version")) {
	print_version_info();
	return 0;
      }
      
      const bool verbose    = parser.has("-v") || parser.has("--verbose");
      const bool robust     = parser.has("-a") || parser.has("--all");
      const bool conformity = parser.has("--conformity");
      
      CPUNIT_ITRACE("EntryPoint - verbose="<<verbose<<" robust="<<robust<<" conformity="<<conformity);
      
      bool conform = true;
      if (conformity) {
	std::vector<std::string> conf_patterns = get_conformity_format(parser);
	const int num_conformity_breaches = conformity_report(patterns, conf_patterns[0], conf_patterns[1], conf_patterns[2], verbose, std::cout);
	std::cout<<"There where "<<num_conformity_breaches<<" conformity breaches."<<std::endl;
	conform = num_conformity_breaches == 0;
      }

      const std::string report_format = parser.value_of<std::string>(error_format_token);
      const double max_time = parser.value_of<double>(max_time_token);
      const std::vector<cpunit::ExecutionReport> result = cpunit::TestExecutionFacade().execute(patterns, max_time, verbose, robust);
      bool all_well = report_result(result, report_format, std::cout);
      
      int exit_value = 0;
      if (!all_well) {
	exit_value |= 0x1;
      }
      if(!conform) {
	exit_value |= 0x2;
      }
      return exit_value;
    } catch (AssertionException &e) {
      std::cout<<"Terminated due to AssertionException: "<<std::endl<<e.what()<<std::endl;
      return 1;
    }
  }
Пример #6
0
/* parser for individual options - fills in a struct cmdline_args */
static error_t parse_option(int key, char *arg, struct argp_state *state)
{
  /* get a shorthand to the command line argument structure, part of state */
  struct cmdline_args *arguments=state->input;

  switch (key) {
  case ARGP_KEY_ARG: /* handle argument (not option) */
    switch (state->arg_num) {
    case 0:
      arguments->server=arg;
      break;

    case 1:
      arguments->rp_realm=arg;
      break;

    case 2:
      arguments->target_realm=arg;
      break;

    case 3:
      arguments->community=arg;
      break;

    case 4:
      arguments->port=strtol(arg, NULL, 10); /* optional */
      break;

    default:
      /* too many arguments */
      argp_usage(state);
    }
    break;

  case ARGP_KEY_END: /* no more arguments */
    if (state->arg_num < 4) {
      /* not enough arguments encountered */
      argp_usage(state);
    }
    break;

  case 'v':
    print_version_info();
    exit(0);

  default:
    return ARGP_ERR_UNKNOWN;
  }

  return 0; /* success */
}
Пример #7
0
void init(){
  print_version_info();

  print_err("start init");
  vec2 points[NumPoints];

  // Specifiy the vertices for a triangle
  vec2 vertices[3] = {
      vec2( -1.0, -1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, -1.0 )
  };

  // Select an arbitrary initial point inside of the triangle
  points[0] = vec2( 0.25, 0.50 );

  // compute and store N-1 new points
  for ( int i = 1; i < NumPoints; ++i ) {
      int j = rand() % 3;   // pick a vertex at random

      // Compute the point halfway between the selected vertex
      //   and the previous point
      points[i] = ( points[i - 1] + vertices[j] ) / 2.0;
  }

  // print_err("finish making points");
  // Create a vertex array object
  GLuint vao[1];
  glGenVertexArraysAPPLE( 1, vao );
  glBindVertexArrayAPPLE( vao[0] );
  // print_err("gen and bind vertex arrays");
  

  // Create and initialize a buffer object
  GLuint buffer;
  glGenBuffers( 1, &buffer );
  glBindBuffer( GL_ARRAY_BUFFER, buffer );
  glBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW );
  // print_err("bind buffer and buffer data");

  // Load shaders and use the resulting shader program
  GLuint program = InitShader( "vertex1.glsl", "frag1.glsl" );
  glUseProgram(program);
  print_err("glUseProgram");

  // Initialize the vertex position attribute from the vertex shader
  GLuint loc = glGetAttribLocation( program, "vPosition" );
  glEnableVertexAttribArray( loc );
  glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0,
                         BUFFER_OFFSET(0) );

  glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background
}
Пример #8
0
int main(int argc, char** argv) {
  
  setup_error_handling();
  
  if (argc > 1) {
    int* script_argc = (int*)malloc(sizeof(int));
    char** script_and_args = parseopts(argc, argv, script_argc);
    if (*(script_argc)) {
      return script(*(script_argc), script_and_args);
    }
    return 0;
  } else {
    print_version_info(argv[0]);
    return prompt();
  }
}
Пример #9
0
int main(int argc, char **argv)
{
    while (*++argv)
        if (!strcmp(*argv, "-r"))
            do_the_relocs = 1;
        else if (!strcmp(*argv, "-?"))
          {
              fputs("usage: pe_map [-r] file ...\n", stderr);
              return EXIT_FAILURE;
          }
        else
          {
              HANDLE hFile, hMapping;
              void *basepointer;
              printf("filename: %s\n", *argv);
              if ((hFile = CreateFile(*argv, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE)
                {
                    puts("(could not open)");
                    return EXIT_FAILURE;
                }
              if (!(hMapping = CreateFileMapping(hFile, 0, PAGE_READONLY | SEC_COMMIT, 0, 0, 0)))
                {
                    puts("(mapping failed)");
                    CloseHandle(hFile);
                    return EXIT_FAILURE;
                }
              if (!(basepointer = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0)))
                {
                    puts("(view failed)");
                    CloseHandle(hMapping);
                    CloseHandle(hFile);
                    return EXIT_FAILURE;
                }
              map_exe(basepointer);
              UnmapViewOfFile(basepointer);
              CloseHandle(hMapping);
              CloseHandle(hFile);
              puts("\nVersion Info:");
              print_version_info(*argv);
          }
    return EXIT_SUCCESS;
}
int player_init(void)
{
    print_version_info();
    update_loglevel_setting();
    /*register all formats and codecs*/
    ffmpeg_init();

    player_id_pool_init();

    codec_audio_basic_init();

    /*register all support decoder */
    ts_register_stream_decoder();
    es_register_stream_decoder();
    ps_register_stream_decoder();
    rm_register_stream_decoder();
    audio_register_stream_decoder();
    video_register_stream_decoder();

    return PLAYER_SUCCESS;
}
Пример #11
0
static P4VOID usage( void )
{
    print_version_info();
    printf("p4 usage: %s [p4 options]\n", pgm);
    printf("Valid p4 options:\n");
    printf("\t-p4help            get this message\n");
    printf("\t-p4pg      <file>  set procgroup file\n");
    printf("\t-p4dbg    <level>  set debug level\n");
    printf("\t-p4rdbg   <level>  set remote debug level\n");
    printf("\t-p4gm      <size>  set globmemsize\n");
    printf("\t-p4dmn   <domain>  set domainname\n");
    printf("\t-p4out     <file>  set output file for master\n");
    printf("\t-p4rout    <file>  set output file prefix for remote masters\n");
    printf("\t-p4ssport <port#>  set private port number for secure server\n");
    printf("\t-p4norem           don't start remote processes\n");
    printf("\t-p4sctrl <string>  set socket control features\n");
#ifdef ALOG_TRACE
    printf("\t-p4log             enable internal p4 logging by alog\n");
#endif
    printf("\t-p4version         print current p4 version number\n");
    printf("\n");
    exit(-1);

}
Пример #12
0
int main(int argc, char **argv) {
    int opt;
    struct augeas *aug;
    char *loadpath = NULL;
    size_t loadpathlen = 0;
    enum {
        VAL_NO_STDINC = CHAR_MAX + 1,
        VAL_NO_TYPECHECK = VAL_NO_STDINC + 1,
        VAL_VERSION = VAL_NO_TYPECHECK + 1
    };
    struct option options[] = {
        { "help",      0, 0, 'h' },
        { "include",   1, 0, 'I' },
        { "trace",     0, 0, 't' },
        { "nostdinc",  0, 0, VAL_NO_STDINC },
        { "notypecheck",  0, 0, VAL_NO_TYPECHECK },
        { "version",  0, 0, VAL_VERSION },
        { 0, 0, 0, 0}
    };
    int idx;
    unsigned int flags = AUG_TYPE_CHECK|AUG_NO_MODL_AUTOLOAD;
    progname = argv[0];

    setlocale(LC_ALL, "");
    while ((opt = getopt_long(argc, argv, "hI:t", options, &idx)) != -1) {
        switch(opt) {
        case 'I':
            argz_add(&loadpath, &loadpathlen, optarg);
            break;
        case 't':
            flags |= AUG_TRACE_MODULE_LOADING;
            break;
        case 'h':
            usage();
            break;
        case VAL_NO_STDINC:
            flags |= AUG_NO_STDINC;
            break;
        case VAL_NO_TYPECHECK:
            flags &= ~(AUG_TYPE_CHECK);
            break;
        case VAL_VERSION:
            print_version = true;
            break;
        default:
            usage();
            break;
        }
    }

    if (!print_version && optind >= argc) {
        fprintf(stderr, "Expected .aug file\n");
        usage();
    }

    argz_stringify(loadpath, loadpathlen, PATH_SEP_CHAR);
    aug = aug_init(NULL, loadpath, flags);
    if (aug == NULL) {
        fprintf(stderr, "Memory exhausted\n");
        return 2;
    }

    if (print_version) {
        print_version_info(aug);
        return EXIT_SUCCESS;
    }

    if (__aug_load_module_file(aug, argv[optind]) == -1) {
        fprintf(stderr, "%s\n", aug_error_message(aug));
        const char *s = aug_error_details(aug);
        if (s != NULL) {
            fprintf(stderr, "%s\n", s);
        }
        exit(EXIT_FAILURE);
    }

    aug_close(aug);
    free(loadpath);
}
Пример #13
0
void initialize_board(void) {
  volatile unsigned long delay = 0xFFFF;

#ifdef BUSPIRATEV3
  /* Set clock divider to 0. */
  CLKDIVbits.RCDIV0 = 0;

  /* All pins are digital. */
  AD1PCFG = 0xFFFF;
#elif defined(BUSPIRATEV4)

  /* Disable nested interrupts. */
  INTCON1bits.NSTDIS = ON;

  /* Set PLL prescaler to 1:1 ratio. */
  CLKDIV = 0x0000;
  BP_LEDUSB_DIR = OUTPUT;

  /* Initialize program space visibility. */
  CORCONbits.PSV = ON;

  /* Map top part of the firmware. */
  PSVPAG = 0;

  /* Disable secondary oscillator. */
  OSCCONbits.SOSCEN = OFF;

  /* Set pins B0, B1, B2, B5, and B15 as analog, rest are digital. */
  AD1PCFGL = 0x7FD8;

  /* Only enable Vbg/2 channel for input scan. */
  AD1PCFGH = 0x0002;
#endif /* BUSPIRATEV3 || BUSPIRATEV4 */

  /* Disable secondary oscillator. */
  OSCCONbits.SOSCEN = OFF;

  /* Wait a bit. */
  while (delay--) {
  }

/* Set up the UART port pins. */

#ifdef BUSPIRATEV3
  BP_TERM_RX = BP_TERM_RX_RP;
  BP_TERM_TX_RP = BP_TERM_TX;
#endif /* BUSPIRATEV3 */

  /* Set the UART port speed to 115200 bps. */
  bus_pirate_configuration.terminal_speed = 8;

  /* Default to print numbers in hexadecimal format. */
  bus_pirate_configuration.display_mode = HEX;

  /* Start from a known, clear state. */
  bp_reset_board_state();

#ifdef BUSPIRATEV3
  /* Initialize the internal UART port. */
  user_serial_initialise();
#endif /* BUSPIRATEV3 */

#if defined(BUSPIRATEV4)

  /* Initialize the USB-based serial port. */

  initCDC();
  usb_init(cdc_device_descriptor, cdc_config_descriptor, cdc_str_descs,
           USB_NUM_STRINGS);
  usb_start();
#endif /* BUSPIRATEV4 */

#ifdef BUSPIRATEV3
  /* Turn pull-ups ON. */
  CNPU1bits.CN6PUE = ON;
  CNPU1bits.CN7PUE = ON;
#endif /* BUSPIRATEV3 */

  /* Read device type and revision. */

  bus_pirate_configuration.device_type =
      bp_read_from_flash(DEV_ADDR_UPPER, DEV_ADDR_TYPE);
  bus_pirate_configuration.device_revision =
      bp_read_from_flash(DEV_ADDR_UPPER, DEV_ADDR_REV);

#ifdef BUSPIRATEV3
  /* Get the revision identifier. */
  bus_pirate_configuration.hardware_version =
      BPV3_HARDWARE_VERSION_TABLE[(PORTB >> 2) & 0b00000011];

  /* Turn pull-ups OFF. */
  CNPU1bits.CN6PUE = OFF;
  CNPU1bits.CN7PUE = OFF;
#else
  bus_pirate_configuration.hardware_version = 0;
#endif /* BUSPIRATEV3 */

  bus_pirate_configuration.quiet = OFF;
  mode_configuration.numbits = 8;

#ifdef BP_ENABLE_BASIC_SUPPORT
  bp_basic_initialize();
#endif /* BP_ENABLE_BASIC_SUPPORT */

  /* Move to page #0. */
  TBLPAG = 0;

#ifndef BUSPIRATEV4
  bpBR;
  print_version_info();
#endif /* !BUSPIRATEV4 */
}
Пример #14
0
int main (int argc, char *argv[])
{
        HTTPMgmt *httpmgmt;
        HTTPStreaming *httpstreaming;
        GMainLoop *loop;
        GOptionContext *ctx;
        GError *err = NULL;
        gboolean foreground;
        struct rlimit rlim;
        GDateTime *datetime;
        gchar exe_path[512], *date;

        ctx = g_option_context_new (NULL);
        g_option_context_add_main_entries (ctx, options, NULL);
        g_option_context_add_group (ctx, gst_init_get_option_group ());
        if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
                g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
                exit (1);
        }
        g_option_context_free (ctx);
        GST_DEBUG_CATEGORY_INIT (GSTREAMILL, "gstreamill", 0, "gstreamill log");

        if (version) {
                print_version_info ();
                exit (0);
        }

        /* stop gstreamill. */
        if (stop) {
                gchar *pid_str;
                gint pid;

                g_file_get_contents (PID_FILE, &pid_str, NULL, NULL);
                if (pid_str == NULL) {
                        g_print ("File %s not found, check if gstreamill is running.\n", PID_FILE);
                        exit (1);
                }
                pid = atoi (pid_str);
                g_free (pid_str);
                g_print ("stoping gstreamill with pid %d ...\n", pid);
                kill (pid, SIGTERM);
                exit (0);
        }

        /* readlink exe path before setuid, on CentOS, readlink exe path after setgid/setuid failure on permission denied */
        memset (exe_path, '\0', sizeof (exe_path));
        if (readlink ("/proc/self/exe", exe_path, sizeof (exe_path)) == -1) {
                g_print ("Read /proc/self/exe error: %s", g_strerror (errno));
                exit (2);
        }

        if (prepare_gstreamill_run_dir () != 0) {
                g_print ("Can't create gstreamill run directory\n");
                exit (3);
        }
/*
        if (set_user_and_group () != 0) {
                g_print ("set user and group failure\n");
                exit (4);
        }
*/
        if (job_file != NULL) {
                /* gstreamill command with job, run in foreground */
                foreground = TRUE;

        } else {
                /* gstreamill command without job, run in background */
                foreground = FALSE;
        }

        if (gst_debug_get_default_threshold () < GST_LEVEL_WARNING) {
                gst_debug_set_default_threshold (GST_LEVEL_WARNING);
        }

        /* initialize ts segment static plugin */
        if (!gst_plugin_register_static (GST_VERSION_MAJOR,
                                         GST_VERSION_MINOR,
                                         "tssegment",
                                         "ts segment plugin",
                                         ts_segment_plugin_init,
                                         "0.1.0",
                                         "GPL",
                                         "GStreamer",
                                         "GStreamer",
                                         "http://gstreamer.net/")) {
                GST_ERROR ("registe tssegment error");
                exit (17);
        }

        /* subprocess, create_job_process */
        if (shm_name != NULL) {
                gint fd;
                gchar *job_desc, *p;
                Job *job;
                gchar *log_path, *name;
                gint ret;

                /* set subprocess maximum of core file */
                rlim.rlim_cur = 0;
                rlim.rlim_max = 0;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }

                /* read job description from share memory */
                job_desc = NULL;
                fd = shm_open (shm_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
                if (ftruncate (fd, job_length) == -1) {
                        exit (5);
                }
                p = mmap (NULL, job_length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
                job_desc = g_strdup (p);

                if ((job_desc != NULL) && (!jobdesc_is_valid (job_desc))) {
                        exit (6);
                }

                /* initialize log */
                name = (gchar *)jobdesc_get_name (job_desc);
                if (!jobdesc_is_live (job_desc)) {
                        gchar *p;

                        p = jobdesc_get_log_path (job_desc);
                        log_path = g_build_filename (p, "gstreamill.log", NULL);
                        g_free (p);

                } else {
                        log_path = g_build_filename (log_dir, name, "gstreamill.log", NULL);
                }
                ret = init_log (log_path);
                g_free (log_path);
                if (ret != 0) {
                        exit (7);
                }

                /* launch a job. */
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s starting ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                job = job_new ("name", name, "job", job_desc, NULL);
                job->is_live = jobdesc_is_live (job_desc);
                job->eos = FALSE;
                loop = g_main_loop_new (NULL, FALSE);

                GST_INFO ("Initializing job ...");
                if (job_initialize (job, TRUE) != 0) {
                        GST_ERROR ("initialize job failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job done");

                GST_INFO ("Initializing job's encoders output ...");
                if (job_encoders_output_initialize (job) != 0) {
                        GST_ERROR ("initialize job encoders' output failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job's encoders output done");

                GST_INFO ("Starting job ...");
                if (job_start (job) != 0) {
                        GST_ERROR ("start livejob failure, exit");
                        exit (9);
                }
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s started ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                g_free (name);
                g_free (job_desc);

                signal (SIGPIPE, SIG_IGN);
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_job);

                g_main_loop_run (loop);

        } else {
                /* set parent process maximum of core file */
                rlim.rlim_cur = RLIM_INFINITY;
                rlim.rlim_max = RLIM_INFINITY;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }
        }

        /* run in background? */
        if (!foreground) {
                gchar *path;
                gint ret;

                /* pid file exist? */
                if (g_file_test (PID_FILE, G_FILE_TEST_EXISTS)) {
                        g_print ("file %s found, gstreamill already running !!!\n", PID_FILE);
                        exit (10);
                }

                /* media directory */
                path = g_strdup_printf ("%s/dvr", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create DVR directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create DVR directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/in", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/out", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);

                /* log to file */
                path = g_build_filename (log_dir, "gstreamill.log", NULL);
                ret = init_log (path);
                g_free (path);
                if (ret != 0) {
                        g_print ("Init log error, ret %d.\n", ret);
                        exit (11);
                }

                /* daemonize */
                if (daemon (0, 0) != 0) {
                        fprintf (_log->log_hd, "Failed to daemonize");
                        remove_pid_file ();
                        exit (1);
                }

                /* create pid file */
                if (create_pid_file () != 0) {
                        exit (1);
                }

                /* customize signal */
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_gstreamill);

                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : gstreamill started ***\n\n", date);
                g_free (date);
                g_date_time_unref (datetime);
        }

        /* ignore SIGPIPE */
        signal (SIGPIPE, SIG_IGN);

        loop = g_main_loop_new (NULL, FALSE);

        /* gstreamill */
        gstreamill = gstreamill_new ("daemon", !foreground, "log_dir", log_dir, "exe_path", exe_path, NULL);
        if (gstreamill_start (gstreamill) != 0) {
                GST_ERROR ("start gstreamill error, exit.");
                remove_pid_file ();
                exit (12);
        }

        /* httpstreaming, pull */
        httpstreaming = httpstreaming_new ("gstreamill", gstreamill, "address", http_streaming, NULL);
        if (httpstreaming_start (httpstreaming, 10) != 0) {
                GST_ERROR ("start httpstreaming error, exit.");
                remove_pid_file ();
                exit (13);
        }

        if (!foreground) {
                /* run in background, management via http */
                httpmgmt = httpmgmt_new ("gstreamill", gstreamill, "address", http_mgmt, NULL);
                if (httpmgmt_start (httpmgmt) != 0) {
                        GST_ERROR ("start http mangment error, exit.");
                        remove_pid_file ();
                        exit (14);
                }

        } else {
                /* run in foreground, start job */
                gchar *job, *p, *result;
                JSON_Value *val;
                JSON_Object *obj;

                /* ctrl-c, stop gstreamill */
                signal (SIGINT, stop_gstreamill);

                /* ctrl-\, stop gstreamill */
                signal (SIGQUIT, stop_gstreamill);

                if (!g_file_get_contents (job_file, &job, NULL, NULL)) {
                        GST_ERROR ("Read job file %s error.", job_file);
                        exit (15);
                }
                p = gstreamill_job_start (gstreamill, job);
                val = json_parse_string (p);
                obj = json_value_get_object (val);
                result = (gchar *)json_object_get_string (obj, "result");
                GST_INFO ("start job result: %s.", result);
                if (g_strcmp0 (result, "success") != 0) {
                        exit (16);
                }
                json_value_free (val);
                g_free (p);
        }

        g_main_loop_run (loop);

        return 0;
}
Пример #15
0
P4VOID process_args(int *argc, char **argv)
{
    int i,c,nextarg;
    FILE *fp;
    char *s, **a;
    struct p4_procgroup_entry *pe;

    if (!argc || !argv) {
	/* Failure if either argc or argv are null */
        p4_error( "Command-line arguments are missing",0 );
    }

    /* Put the name of the called program (according to the args) into pgm */
    s = (char *)  rindex(*argv, '/');
    if (s)
	strcpy(pgm, s + 1);
    else
	strcpy(pgm, *argv);

    /* Set all command line flags (except procgroup) to their defaults */
    p4_debug_level = 0;
    p4_remote_debug_level = 0;
    bm_outfile[0] = '\0';
    procgroup_file[0] = '\0';
    p4_wd[0] = '\0';
    strcpy(local_domain, "");
    p4_myname_in_procgroup[0] = '\0';
    hand_start_remotes = P4_FALSE;
    execer_starting_remotes = P4_FALSE;
    execer_id[0] = '\0';
    execer_masthost[0] = '\0';
#ifdef OLD_EXECER
    execer_jobname[0] = '\0';
#endif
    execer_mynodenum = 0;
    execer_mastport = 0;
    execer_pg = NULL;

    /* Move to last argument, so that we can go backwards. */
    a = &argv[*argc - 1];

    /*
     * Loop backwards through arguments, catching the ones that start with
     * '-'.  Backwards is more efficient when you are stripping things out.
     */
    for (c = (*argc); c > 1; c--, a--)
    {
	if (**a != '-')
	    continue;

        if (strcmp(*a, "-execer_id") == 0)
        {
	    /*
	     * Format of the rest of the args, example job:
	     *   node00:1 + node01:3 + node02:1
	     * Big master:
	     * a.out -execer_id mpiexec -master_host node00 -my_hostname node00
	     *   -my_nodenum 0 -my_numprocs 1 -total_numnodes 3 -mastport 4444
	     *  -remote_info node01 3 node02 1
	     * Remote masters:
	     * a.out -execer_id mpiexec -master_host node00 -my_hostname node01
	     *  -my_nodenum 1 -my_numprocs 3 -total_numnodes 3 -master_port 5555
	     * a.out -execer_id mpiexec -master_host node00 -my_hostname node02
	     *  -my_nodenum 2 -my_numprocs 1 -total_numnodes 3 -master_port 5555
	     *
	     * Master will be started first, then report its listening
	     * socket, then slaves can be started all at once in any order.
	     */
            execer_starting_remotes = P4_TRUE;
            strcpy(execer_id,*(a+1));
            strcpy(execer_masthost,*(a+3));
            strcpy(execer_myhost,*(a+5));
            execer_mynodenum = atoi(*(a+7));
            execer_mynumprocs = atoi(*(a+9));
	    execer_numtotnodes = atoi(*(a+11));
#ifdef OLD_EXECER
            strcpy(execer_jobname,*(a+13));
#else
	    execer_mastport = atoi(*(a+13));
	    nextarg = 14;
#endif
	    if (execer_mynodenum == 0)
	    {
		execer_pg = p4_alloc_procgroup();
		pe = execer_pg->entries;
		strcpy(pe->host_name,execer_myhost);
		pe->numslaves_in_group = execer_mynumprocs - 1;
		strcpy(pe->slave_full_pathname,argv[0]);
		pe->username[0] = '\0'; /* unused */
		execer_pg->num_entries++;
		for (i=0; i < (execer_numtotnodes-1); i++)
		{
		    if (i == 0)
			++nextarg;  /* "-remote_info" fake arg */
		    pe++;
		    strcpy(pe->host_name,*(a+nextarg));
		    nextarg++;
#ifdef OLD_EXECER
		    nextarg++;  /* skip node num */
#endif
		    pe->numslaves_in_group = atoi(*(a+nextarg));
		    nextarg++;
#ifdef OLD_EXECER
		    strcpy(pe->slave_full_pathname,*(a+nextarg)); /* unused */
		    nextarg++;
#else
		    *pe->slave_full_pathname = 0;
#endif
		    pe->username[0] = '\0'; /* unused */

		    execer_pg->num_entries++;
		}
	    }
#ifdef OLD_EXECER
	    else
	    {
		execer_mastport = get_execer_port(execer_masthost);
	    }
#else
	    strip_out_args(a, argc, &c, nextarg);
#endif
            continue;
        }

	if (!strcmp(*a, "-p4pg"))
	{
	    if (bad_arg(a[1]))
		usage();
	    strncpy(procgroup_file, a[1], 256);
	    procgroup_file[255] = 0;
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4wd"))
	{
	    if (bad_arg(a[1]))
		usage();
	    strncpy(p4_wd, a[1], 255);
	    p4_wd[255] = 0;
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4dbg"))
	{
	    if (bad_arg(a[1]))
		usage();
	    p4_debug_level = atoi(a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4ssport"))
	{
	    if (bad_arg(a[1]))
		usage();
	    sserver_port = atoi(a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4rdbg"))
	{
	    if (bad_arg(a[1]))
		usage();
	    p4_remote_debug_level = atoi(a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4gm"))
	{
	    if (bad_arg(a[1]))
		usage();
	    globmemsize = atoi(a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4dmn"))
	{
	    if (bad_arg(a[1]))
		usage();
	    strcpy(local_domain, a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4out"))
	{
	    if (bad_arg(a[1]))
		usage();
	    strncpy(bm_outfile, a[1], 100);
	    bm_outfile[99] = 0;
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4rout"))
	{
	    if (bad_arg(a[1]))
		usage();
	    strncpy(rm_outfile_head, a[1], 100);
	    rm_outfile_head[99] = 0;
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4log"))
	{
	    strip_out_args(a, argc, &c, 1);
	    logging_flag = P4_TRUE;
	    continue;
	}
	if (!strcmp(*a, "-p4norem"))
	{
	    strip_out_args(a, argc, &c, 1);
	    hand_start_remotes = P4_TRUE;
	    continue;
	}
	if (!strcmp(*a, "-p4version"))
	{
	    strip_out_args(a, argc, &c, 1);
	    print_version_info();
	    continue;
	}
	/* Add escape for socket performance controls */
	if (!strcmp( *a, "-p4sctrl" ))
	{
	    if (bad_arg(a[1]))
		usage();
	    p4_socket_control( a[1] );
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}

	if (!strcmp(*a, "-p4yourname"))
	{
	    /* Capture the name that the master is using in its procgroup
	       file.  This really belongs with the various "remote master"
	       arguments, but putting it there will mess up lots of 
	       code.  Using a separate argument for this makes it
	       easier to make this an optional value */
	    if (bad_arg(a[1]))
		usage();
	    strncpy(p4_myname_in_procgroup, a[1], MAXHOSTNAMELEN);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp( *a, "-p4rmrank")) {
	    /* Capture the base rank for this remote master.  That is,
	       the rank of the remote master.  */
	    if (bad_arg(a[1]))
		usage();
	    p4_rm_rank = atoi(a[1]);
	    strip_out_args(a, argc, &c, 2);
	    continue;
	}
	if (!strcmp(*a, "-p4help"))
	    usage();
    }
    if (!execer_starting_remotes) {
	if (procgroup_file[0] == '\0')
	{
	    strncpy(procgroup_file,argv[0],250);
	    procgroup_file[249] = 0;
	    strcat(procgroup_file,".pg");
	    if ((fp = fopen(procgroup_file,"r")) == NULL) {
                /* pgm.pg not there */
		strcpy(procgroup_file, "procgroup");
	    }
	    else
		fclose(fp);
	}
	p4_dprintfl(10,"using procgroup file %s\n",procgroup_file);
    }
}
Пример #16
0
int main(int argc, char* const* argv) {
	static int debug_mode = false;
	static int verbose_mode = false;
	static int interactive_mode = false;
	
	ObjectPtr<Array> require_files = create_array();
	
	while (true)
	{
		int c;
		
		static struct option long_options[] = {
			{"debug",       no_argument,       &debug_mode,       'd'},
			{"version",     no_argument,       NULL,              'v'},
			{"require",     required_argument, NULL,              'r'},
			{"interactive", no_argument,       &interactive_mode,  1 },
			{"verbose",     no_argument,       &verbose_mode,      1 },
			{0,0,0,0}
		};
		
		int option_index = -1;
		
		c = getopt_long(argc, argv, "dvir:", long_options, &option_index);
		if (c < 0)
			break;
		
		switch (c)
		{
			case 'v':
			{
				print_version_info();
				return 0;
			}
			case 'r':
			{
				ObjectPtr<String> filename = create_string_constant(optarg);
				array_push(require_files, filename);
				break;
			}
			case 'i':
			{
				interactive_mode = true;
				break;
			}
			case '?':
				TRAP(); // unknown argument
			default:
				break;
		}
	}
	
	// require first loose argument, unless -- was used
	if (optind < argc && strcmp("--", argv[optind-1]) != 0) {
		ObjectPtr<String> filename = create_string_constant(argv[optind++]);
		array_push(require_files, filename);
	}
	
	// stuff the rest in ARGV
	ObjectPtr<Array> ARGV = create_array_with_size(argc);
	while (optind < argc) {
		ObjectPtr<String> argument = create_string_constant(argv[optind++]);
		array_push(ARGV, argument);
	}
	set_global(snow::sym("ARGV"), ARGV);
	
	for (size_t i = 0; i < array_size(require_files); ++i) {
		ObjectPtr<String> str = array_get(require_files, i);
		ASSERT(str != NULL);
		load(str);
	}
	
	if (interactive_mode) {
		interactive_prompt();
	}
	
	return 0;
}
int main(int argc,char **argv){
    print_version_info();
    return 0;

}