void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name, boostStruct* bst) { int i; Double accuracy; ULong maxIteration; int mode, poolSize; char* p; //parse options for ( i = 1; i < argc; i++) { if ( argv[i][0] != '-') break; if ( ++i >= argc) exit_help(); switch(argv[i-1][1]) { case 'a' : accuracy = atof(argv[i]); bst->tarAccuracy = accuracy; break; case 'i' : maxIteration = atoi(argv[i]); bst->maxIter = maxIteration; break; case 'f' : mode = atoi(argv[i]); bst->fastMode = mode; break; case 's' : poolSize = atoi(argv[i]); bst->fastPoolSize = poolSize; break; default: fprintf(stderr, "unknown option: -%c\n", argv[i-1][1]); exit_help(); break; } } //determine filenames if ( i >= argc) exit_help(); strcpy(input_file_name, argv[i]); if ( i < argc-1) strcpy(model_file_name, argv[i+1]); else { p = strrchr(argv[i], '/'); if ( p == NULL) p = argv[i]; else p++; sprintf(model_file_name, "%s.model", p); } }//end parse_command_line
/* * Read the data file specified and get the version and release number * from it. * * This function also construct the correct RegistryKey from the version information * retrieved. */ void read_datafile(void) { FILE *fp; char *newname; long size; if(!DataFileName) { DataFileName = malloc(strlen(DEFAULT_DATAFILE) + 1); strcpy(DataFileName,DEFAULT_DATAFILE); } /* Is DataFileName relative or absolute ? */ if( (DataFileName[0] != '\\') && (strncmp(DataFileName+1, ":\\", 2)!=0) ) { /* Relative name, we have to prepend RelDir to it. */ if( !RelDir ) { exit_help("Need -reldir when -data filename has relative path."); } else { newname = (char *)malloc(strlen(DataFileName)+strlen(RelDir)+2); assert(newname); sprintf(newname, "%s\\%s", RelDir, DataFileName); free(DataFileName); DataFileName=newname; } } #ifdef _DEBUG fprintf(stderr, "DataFileName: '%s'\n", DataFileName); #endif if( (fp=fopen(DataFileName, "rb")) == NULL) { exit_help("Cannot find the datafile."); } fseek(fp, 0, SEEK_END); size=ftell(fp); fseek(fp, 0, SEEK_SET); Version = (char *)malloc(size+1); Release = (char *)malloc(size+1); assert(Version); assert(Release); if( (fscanf(fp, "%s %s", Version, Release)) == 0) { fclose(fp); exit_help("Format error in datafile."); } fclose(fp); #ifdef _DEBUG fprintf(stderr, "DataFile version: '%s'\n", Version); fprintf(stderr, "DataFile release: '%s'\n", Release); #endif }
/* * Parses MyCommandLine and tries to fill in all the required option variables * (one way or another). */ void parse_commandline(void) { char *cmdline = MyCommandLine; while( *cmdline != '\0' ) { switch( *cmdline ) { case '-': /* Handle both -arg and /arg */ case '/': *cmdline++; if( strnicmp(cmdline, "data", 4) == 0) { DataFileName = unquote_optionarg(cmdline+4, &cmdline); } else if( strnicmp(cmdline, "reldir", 6) == 0) { RelDir = unquote_optionarg(cmdline+6, &cmdline); #ifdef _DEBUG fprintf(stderr, "RelDir: '%s'\n", RelDir); #endif } else if( strnicmp(cmdline, "bootflags", 9) == 0) { BootFlagsFile = unquote_optionarg(cmdline+9, &cmdline); } else if( strnicmp(cmdline, "noconfig", 8) == 0) { NoConfig=TRUE; #ifdef _DEBUG fprintf(stderr, "NoConfig=TRUE\n"); #endif } else { fprintf(stderr, "Unkown option: '%s'\n", cmdline); exit_help("Unknown command line option"); } break; default: cmdline++; break; } } }
/* * Try to make the needed options complete by looking through the data file, * environment variables and registry entries. */ void complete_options(void) { /* Try to find a descent RelDir */ if( !RelDir ) { DWORD sz = 32; while (1) { DWORD nsz; if (RelDir) free(RelDir); RelDir = malloc(sz); if (!RelDir) { fprintf(stderr, "** Error : failed to allocate memory\n"); exit(1); } SetLastError(0); nsz = GetEnvironmentVariable((LPCTSTR) "RELDIR", (LPTSTR) RelDir, sz); if (nsz == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) { free(RelDir); RelDir = NULL; break; } else if (nsz <= sz) break; else sz = nsz; } if (RelDir == NULL) { if(DataFileName) { /* Needs to be absolute for this to work, but we can try... */ read_datafile(); read_registry_keys(); } else { /* Impossible to find all data... */ exit_help("Need either Release directory or an absolute " "datafile name."); } /* Ok, construct our own RelDir from RootDir */ RelDir = (char *) malloc(strlen(RootDir)+strlen(RELEASE_SUBDIR)+1); assert(RelDir); sprintf(RelDir, "%s" RELEASE_SUBDIR, RootDir); } else { read_datafile(); read_registry_keys(); } } else { read_datafile(); read_registry_keys(); } read_bootflags(); #ifdef _DEBUG fprintf(stderr, "RelDir: '%s'\n", RelDir); #endif }
int main(int argc,char *argv[]) { bool verbose = false; bool help = false; int option_index = 0; char c; FILE *stream; stream = freopen("CON", "w", stdout); printf("\nProgram v0.0\n"); while ((c = getopt_long(argc, argv, "vh",long_options, &option_index)) != -1){ switch (c) { case 'v': verbose = true; break; case 'h': help = true; break; default: //printf("unknown option '%c'.\n", optopt); break; } } if(help){ exit_help("\n"); }else{ //Main program myapp.run(); server s; long t1=1, t2=2, t3=3,t4=4; int iret1, iret2,iret3,iret4; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &myapp.thread1, NULL, userinput, (void*) t1); iret2 = pthread_create( &myapp.thread2, NULL, timer, (void*) t2); iret3 = pthread_create( &myapp.thread3, NULL, watchtimer, (void*) t3); iret4 = pthread_create( &myapp.thread4, NULL, serverstart, (void*) &s); pthread_join( myapp.thread1, NULL); pthread_join( myapp.thread2, NULL); pthread_join( myapp.thread3, NULL); pthread_join( myapp.thread4, NULL); printf("Thread 1 returned: %d\n",iret1); printf("Thread 2 returned: %d\n",iret2); printf("Thread 3 returned: %d\n",iret3); printf("Thread 4 returned: %d\n",iret4); pthread_mutex_destroy(&myapp.timemutex); pthread_cond_destroy(&myapp.timecondition); pthread_mutex_destroy(&myapp.syscallmutex); pthread_cond_destroy(&myapp.syscallcondition); } exit(0); }
/* * 'Smart' unquoting of a string: \" becomes " and " becomes (nothing) * Skips any leading spaces and parses up to NULL or end of quoted string. * Calls exit_help() if an unterminated quote is detected. */ char * unquote_optionarg(char *str, char **strp) { char *newstr = (char *)malloc(strlen(str)+1); /* This one is realloc:ed later */ int i = 0, inquote = 0; assert(newstr); assert(str); /* Skip leading spaces */ while( *str == ' ' ) str++; /* Loop while in quote or until EOS or unquoted space */ while( (inquote==1) || ( (*str!=0) && (*str!=' ') ) ) { switch( *str ) { case '\\': /* If we are inside a quoted string we should convert \c to c */ if( inquote && str[1] == '"' ) str++; newstr[i++]=*str++; break; case '"': inquote = 1-inquote; *str++; break; default: newstr[i++]=*str++; break; } if( (*str == 0) && (inquote==1) ) { exit_help("Unterminated quote."); } } newstr[i++] = 0x00; /* Update the supplied pointer (used for continued parsing of options) */ *strp = str; /* Adjust memblock of newstr */ newstr = (char *)realloc(newstr, i); assert(newstr); return(newstr); }
int opt_parse(int argc, char * const * argv, status_data *status) { int opt; const char opt_list[] = "w:vt:s:h"; /* ajouter dump */ while ( (opt = getopt(argc, argv, opt_list)) != -1 ) { switch (opt) { case 'h': exit_help(argv[0]); break; case 'w': status->wisdomfile = optarg; break; case 'v': status->verbose = 1; break; case 't': status->timeout = strtolint('t', optarg); if (status->timeout < 0) { fprintf(stderr, "Timeout must be positive\n"); exit(EXIT_FAILURE); } break; case 's': status->sampling = strtolint('s', optarg); if (status->sampling <= 0) { fprintf(stderr, "Sample duration must be " "positive\n"); exit(EXIT_FAILURE); } break; } } if (!status->sampling) status->sampling = SAMPLE_DURATION; return 0; }
long start_new_node(void) { char *CommandLine; unsigned long i; STARTUPINFO si; DWORD dwExitCode; i = strlen(RelDir) + strlen(Release) + 4; VsnDir = (char *)malloc(i); assert(VsnDir); sprintf(VsnDir, "%s\\%s", RelDir, Release); if( NoConfig ) { i = strlen(BinDir) + strlen(ErlCommandLine) + strlen(BootFlags) + 64; CommandLine = (char *)malloc(i); assert(CommandLine); sprintf(CommandLine, "\"%s\\erl.exe\" -boot \"%s\\start\" %s %s", BinDir, VsnDir, ErlCommandLine, BootFlags); } else { i = strlen(BinDir) + strlen(ErlCommandLine) + strlen(BootFlags) + strlen(VsnDir)*2 + 64; CommandLine = (char *)malloc(i); assert(CommandLine); sprintf(CommandLine, "\"%s\\erl.exe\" -boot \"%s\\start\" -config \"%s\\sys\" %s %s", BinDir, VsnDir, VsnDir, ErlCommandLine, BootFlags); } #ifdef _DEBUG fprintf(stderr, "CommandLine: '%s'\n", CommandLine); #endif /* Initialize the STARTUPINFO structure. */ memset(&si, 0, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.lpTitle = NULL; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); /* Create the new Erlang process */ if( (CreateProcess( NULL, /* pointer to name of executable module */ CommandLine, /* pointer to command line string */ NULL, /* pointer to process security attributes */ NULL, /* pointer to thread security attributes */ TRUE, /* handle inheritance flag */ GetPriorityClass(GetCurrentProcess()), /* creation flags */ NULL, /* pointer to new environment block */ BinDir,/* pointer to current directory name */ &si, /* pointer to STARTUPINFO */ &ErlProcessInfo /* pointer to PROCESS_INFORMATION */ )) == FALSE) { ShowLastError(); exit_help("Failed to start new node"); } #ifdef _DEBUG fprintf(stderr, "Waiting for Erlang to terminate.\n"); #endif if(MsgWaitForMultipleObjects(1,&ErlProcessInfo.hProcess, FALSE, INFINITE, QS_POSTMESSAGE) == WAIT_OBJECT_0+1) { if(PostThreadMessage(ErlProcessInfo.dwThreadId, WM_USER, (WPARAM) 0, (LPARAM) 0)) { /* Wait 10 seconds for erl process to die, elsee terminate it. */ if(WaitForSingleObject(ErlProcessInfo.hProcess, 10000) != WAIT_OBJECT_0) { TerminateProcess(ErlProcessInfo.hProcess,0); } } else { TerminateProcess(ErlProcessInfo.hProcess,0); } } GetExitCodeProcess(ErlProcessInfo.hProcess, &dwExitCode); #ifdef _DEBUG fprintf(stderr, "Erlang terminated.\n"); #endif free(CommandLine); return(dwExitCode); }
/* * Read the bootflags. This file contains extra command line options to erl.exe */ void read_bootflags(void) { FILE *fp; long fsize; char *newname; if(BootFlagsFile) { /* Is BootFlagsFile relative or absolute ? */ if( (BootFlagsFile[0] != '\\') && (strncmp(BootFlagsFile+1, ":\\", 2)!=0) ) { /* Relative name, we have to prepend RelDir\\Version to it. */ if( !RelDir ) { exit_help("Need -reldir when -bootflags " "filename has relative path."); } else { newname = (char *)malloc(strlen(BootFlagsFile)+strlen(RelDir)+strlen(Release)+3); assert(newname); sprintf(newname, "%s\\%s\\%s", RelDir, Release, BootFlagsFile); free(BootFlagsFile); BootFlagsFile=newname; } } #ifdef _DEBUG fprintf(stderr, "BootFlagsFile: '%s'\n", BootFlagsFile); #endif if( (fp=fopen(BootFlagsFile, "rb")) == NULL) { exit_help("Could not open BootFlags file."); } fseek(fp, 0, SEEK_END); fsize=ftell(fp); fseek(fp, 0, SEEK_SET); BootFlags = (char *)malloc(fsize+1); assert(BootFlags); if( (fgets(BootFlags, fsize+1, fp)) == NULL) { exit_help("Error while reading BootFlags file"); } fclose(fp); /* Adjust buffer size */ BootFlags = (char *)realloc(BootFlags, strlen(BootFlags)+1); assert(BootFlags); /* Strip \r\n from BootFlags */ fsize = strlen(BootFlags); while( fsize > 0 && ( (BootFlags[fsize-1] == '\r') || (BootFlags[fsize-1] == '\n') ) ) { BootFlags[--fsize]=0; } } else { /* Set empty BootFlags */ BootFlags = ""; } #ifdef _DEBUG fprintf(stderr, "BootFlags: '%s'\n", BootFlags); #endif }
/* * Read the registry keys we need */ void read_registry_keys(void) { HKEY hReg; ULONG lLen; /* Create the RegistryKey name */ RegistryKey = (char *) malloc(strlen(REGISTRY_BASE) + strlen(Version) + 1); assert(RegistryKey); sprintf(RegistryKey, REGISTRY_BASE "%s", Version); /* We always need to find BinDir */ if( (RegOpenKeyEx(HKEY_LOCAL_MACHINE, RegistryKey, 0, KEY_READ, &hReg)) != ERROR_SUCCESS ) { exit_help("Could not open registry key."); } /* First query size of data */ if( (RegQueryValueEx(hReg, "Bindir", NULL, NULL, NULL, &lLen)) != ERROR_SUCCESS) { exit_help("Failed to query BinDir of release.\n"); } /* Allocate enough space */ BinDir = (char *)malloc(lLen+1); assert(BinDir); /* Retrieve the value */ if( (RegQueryValueEx(hReg, "Bindir", NULL, NULL, (unsigned char *) BinDir, &lLen)) != ERROR_SUCCESS) { exit_help("Failed to query BinDir of release (2).\n"); } #ifdef _DEBUG fprintf(stderr, "Bindir: '%s'\n", BinDir); #endif /* We also need the rootdir, in case we need to build RelDir later */ /* First query size of data */ if( (RegQueryValueEx(hReg, "Rootdir", NULL, NULL, NULL, &lLen)) != ERROR_SUCCESS) { exit_help("Failed to query RootDir of release.\n"); } /* Allocate enough space */ RootDir = (char *) malloc(lLen+1); assert(RootDir); /* Retrieve the value */ if( (RegQueryValueEx(hReg, "Rootdir", NULL, NULL, (unsigned char *) RootDir, &lLen)) != ERROR_SUCCESS) { exit_help("Failed to query RootDir of release (2).\n"); } #ifdef _DEBUG fprintf(stderr, "Rootdir: '%s'\n", RootDir); #endif RegCloseKey(hReg); }
int main(int argc, char **argv) { printf("webtty - monitor and control tty applications using fifos\n\n"); /* Is there no args or is '--help' '-?' or '-h' present ? */ if ((1 == argc) || strstr(argv[1],"--help-?-h")) /* Yes - display the help */ exit_help(); else { FILE *f; int dying_status, dying_pid; /* No - run the program */ name_buffer = (char *)malloc(5+strlen(argv[1])); name_fifo_in = (char *)malloc(5+strlen(argv[1])); name_fifo_out = (char *)malloc(5+strlen(argv[1])); name_pid = (char *)malloc(5+strlen(argv[1])); name_admin = (char *)malloc(1+strlen(argv[2])); process_id = (char *)malloc(9+1+strlen(argv[1])); strcpy(name_admin, argv[2]); sprintf(process_id, "webtty[%s]",argv[1]); openlog(process_id,LOG_PERROR,0); /* launch application */ pid_terminal = handle_terminal(&terminal, &argv[3]); /* handover to main process id to php */ strcpy(name_pid, argv[1]); strcat(name_pid, "_pid"); f = fopen(name_pid,"w"); fprintf(f,"%d\n",pid_terminal); fclose(f); /* launch buffer handling */ strcpy(name_buffer,argv[1]); strcat(name_buffer,"_buf"); pid_buffer = handle_output_buffer(terminal,name_buffer); /* launch fifo output handling */ strcpy(name_fifo_out, argv[1]); strcat(name_fifo_out, "_out"); mkfifo(name_fifo_out,0777); pid_fifo_out = handle_output_fifo(name_buffer, name_fifo_out); /* launch fifo input handling */ strcpy(name_fifo_in, argv[1]); strcat(name_fifo_in, "_in"); mkfifo(name_fifo_in,0777); pid_fifo_in = handle_input_fifo(name_fifo_in,terminal); DEBUG(LID, "new process t:%d b:%d i:%d o:%d",pid_terminal,pid_buffer,pid_fifo_in,pid_fifo_out); /* establish signal handler */ if (signal (SIGINT, fatal_error_signal) == SIG_IGN) signal (SIGINT, SIG_IGN); if (signal (SIGHUP, fatal_error_signal) == SIG_IGN) signal (SIGHUP, SIG_IGN); if (signal (SIGTERM, fatal_error_signal) == SIG_IGN) signal (SIGTERM, SIG_IGN); /* wait for any children to die */ int dying_id = waitpid (-1, 0, 0); DEBUG(LID, "dying process %d",dying_id); if (pid_fifo_in == dying_id) pid_fifo_in=0; if (pid_fifo_out == dying_id) pid_fifo_out=0; if (pid_buffer == dying_id) pid_buffer=0; if (pid_terminal == dying_id) pid_terminal=0; /* cleanup and kill rest of children in signal handler */ raise (SIGTERM); /* wait for all to die, before returning */ wait (0); } DEBUG(LID, "ended"); }
/** Hello, this is main. * \param argc Who knows. * \param argv Who knows. * \return EXIT_SUCCESS I hope. */ int main(int argc, char **argv) { char *confpath = NULL; int xfd, i, screen_nbr, opt, colors_nbr; xcolor_init_request_t colors_reqs[2]; ssize_t cmdlen = 1; xdgHandle xdg; xcb_generic_event_t *event; static struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "config", 1, NULL, 'c' }, { "check", 0, NULL, 'k' }, { NULL, 0, NULL, 0 } }; /* event loop watchers */ ev_io xio = { .fd = -1 }; ev_check xcheck; ev_prepare a_refresh; ev_signal sigint; ev_signal sigterm; ev_signal sighup; /* clear the globalconf structure */ p_clear(&globalconf, 1); globalconf.keygrabber = LUA_REFNIL; globalconf.mousegrabber = LUA_REFNIL; buffer_init(&globalconf.startup_errors); /* save argv */ for(i = 0; i < argc; i++) cmdlen += a_strlen(argv[i]) + 1; globalconf.argv = p_new(char, cmdlen); a_strcpy(globalconf.argv, cmdlen, argv[0]); for(i = 1; i < argc; i++) { a_strcat(globalconf.argv, cmdlen, " "); a_strcat(globalconf.argv, cmdlen, argv[i]); } /* Text won't be printed correctly otherwise */ setlocale(LC_CTYPE, ""); /* Get XDG basedir data */ xdgInitHandle(&xdg); /* init lua */ luaA_init(&xdg); /* check args */ while((opt = getopt_long(argc, argv, "vhkc:", long_options, NULL)) != -1) switch(opt) { case 'v': eprint_version(); break; case 'h': exit_help(EXIT_SUCCESS); break; case 'k': if(!luaA_parserc(&xdg, confpath, false)) { fprintf(stderr, "✘ Configuration file syntax error.\n"); return EXIT_FAILURE; } else { fprintf(stderr, "✔ Configuration file syntax OK.\n"); return EXIT_SUCCESS; } case 'c': if(a_strlen(optarg)) confpath = a_strdup(optarg); else fatal("-c option requires a file name"); break; } globalconf.loop = ev_default_loop(0); ev_timer_init(&globalconf.timer, &luaA_on_timer, 0., 0.); /* register function for signals */ ev_signal_init(&sigint, exit_on_signal, SIGINT); ev_signal_init(&sigterm, exit_on_signal, SIGTERM); ev_signal_init(&sighup, restart_on_signal, SIGHUP); ev_signal_start(globalconf.loop, &sigint); ev_signal_start(globalconf.loop, &sigterm); ev_signal_start(globalconf.loop, &sighup); ev_unref(globalconf.loop); ev_unref(globalconf.loop); ev_unref(globalconf.loop); struct sigaction sa = { .sa_handler = signal_fatal, .sa_flags = 0 }; sigemptyset(&sa.sa_mask); sigaction(SIGSEGV, &sa, 0); /* XLib sucks */ XkbIgnoreExtension(True); /* X stuff */ globalconf.display = XOpenDisplay(NULL); if (globalconf.display == NULL) fatal("cannot open display"); globalconf.default_screen = XDefaultScreen(globalconf.display); globalconf.connection = XGetXCBConnection(globalconf.display); /* Double checking then everything is OK. */ if(xcb_connection_has_error(globalconf.connection)) fatal("cannot open display"); /* Prefetch all the extensions we might need */ xcb_prefetch_extension_data(globalconf.connection, &xcb_big_requests_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_test_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_randr_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_shape_id); /* initialize dbus */ a_dbus_init(); /* Get the file descriptor corresponding to the X connection */ xfd = xcb_get_file_descriptor(globalconf.connection); ev_io_init(&xio, &a_xcb_io_cb, xfd, EV_READ); ev_io_start(globalconf.loop, &xio); ev_check_init(&xcheck, &a_xcb_check_cb); ev_check_start(globalconf.loop, &xcheck); ev_unref(globalconf.loop); ev_prepare_init(&a_refresh, &a_refresh_cb); ev_prepare_start(globalconf.loop, &a_refresh); ev_unref(globalconf.loop); /* Grab server */ xcb_grab_server(globalconf.connection); /* Make sure there are no pending events. Since we didn't really do anything * at all yet, we will just discard all events which we received so far. * The above GrabServer should make sure no new events are generated. */ xcb_aux_sync(globalconf.connection); while ((event = xcb_poll_for_event(globalconf.connection)) != NULL) { /* Make sure errors are printed */ uint8_t response_type = XCB_EVENT_RESPONSE_TYPE(event); if(response_type == 0) event_handle(event); p_delete(&event); } for(screen_nbr = 0; screen_nbr < xcb_setup_roots_length(xcb_get_setup(globalconf.connection)); screen_nbr++) { const uint32_t select_input_val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT; /* This causes an error if some other window manager is running */ xcb_change_window_attributes(globalconf.connection, xutil_screen_get(globalconf.connection, screen_nbr)->root, XCB_CW_EVENT_MASK, &select_input_val); } /* Need to xcb_flush to validate error handler */ xcb_aux_sync(globalconf.connection); /* Process all errors in the queue if any. There can be no events yet, so if * this function returns something, it must be an error. */ if (xcb_poll_for_event(globalconf.connection) != NULL) fatal("another window manager is already running"); /* Prefetch the maximum request length */ xcb_prefetch_maximum_request_length(globalconf.connection); /* check for xtest extension */ const xcb_query_extension_reply_t *xtest_query; xtest_query = xcb_get_extension_data(globalconf.connection, &xcb_test_id); globalconf.have_xtest = xtest_query->present; /* Allocate the key symbols */ globalconf.keysyms = xcb_key_symbols_alloc(globalconf.connection); xcb_get_modifier_mapping_cookie_t xmapping_cookie = xcb_get_modifier_mapping_unchecked(globalconf.connection); /* init atom cache */ atoms_init(globalconf.connection); /* init screens information */ screen_scan(); /* init default font and colors */ colors_reqs[0] = xcolor_init_unchecked(&globalconf.colors.fg, "black", sizeof("black") - 1); colors_reqs[1] = xcolor_init_unchecked(&globalconf.colors.bg, "white", sizeof("white") - 1); globalconf.font = draw_font_new("sans 8"); for(colors_nbr = 0; colors_nbr < 2; colors_nbr++) xcolor_init_reply(colors_reqs[colors_nbr]); xutil_lock_mask_get(globalconf.connection, xmapping_cookie, globalconf.keysyms, &globalconf.numlockmask, &globalconf.shiftlockmask, &globalconf.capslockmask, &globalconf.modeswitchmask); /* Get the window tree associated to this screen */ const int screen_max = xcb_setup_roots_length(xcb_get_setup(globalconf.connection)); xcb_query_tree_cookie_t tree_c[screen_max]; /* do this only for real screen */ for(screen_nbr = 0; screen_nbr < screen_max; screen_nbr++) { /* select for events */ const uint32_t change_win_vals[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_FOCUS_CHANGE }; tree_c[screen_nbr] = xcb_query_tree_unchecked(globalconf.connection, xutil_screen_get(globalconf.connection, screen_nbr)->root); xcb_change_window_attributes(globalconf.connection, xutil_screen_get(globalconf.connection, screen_nbr)->root, XCB_CW_EVENT_MASK, change_win_vals); ewmh_init(screen_nbr); systray_init(screen_nbr); } /* init spawn (sn) */ spawn_init(); /* we will receive events, stop grabbing server */ xcb_ungrab_server(globalconf.connection); /* Parse and run configuration file */ if (!luaA_parserc(&xdg, confpath, true)) fatal("couldn't find any rc file"); scan(tree_c); xcb_flush(globalconf.connection); /* main event loop */ ev_loop(globalconf.loop, 0); /* cleanup event loop */ ev_ref(globalconf.loop); ev_check_stop(globalconf.loop, &xcheck); ev_ref(globalconf.loop); ev_prepare_stop(globalconf.loop, &a_refresh); ev_ref(globalconf.loop); ev_io_stop(globalconf.loop, &xio); awesome_atexit(false); return EXIT_SUCCESS; }
/* * Try to make the needed options complete by looking through the data file, * environment variables and registry entries. */ void complete_options(void) { /* Try to find a descent RelDir */ if( !RelDir ) { DWORD sz = 32; while (1) { DWORD nsz; if (RelDir) free(RelDir); RelDir = malloc(sz); if (!RelDir) { fprintf(stderr, "** Error : failed to allocate memory\n"); exit(1); } SetLastError(0); nsz = GetEnvironmentVariable((LPCTSTR) "RELDIR", (LPTSTR) RelDir, sz); if (nsz == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) { free(RelDir); RelDir = NULL; break; } else if (nsz <= sz) break; else sz = nsz; } if (RelDir == NULL) { if (!RootDir) { /* Impossible to find all data... */ exit_help("Need either Root directory nor Release directory."); } /* Ok, construct our own RelDir from RootDir */ RelDir = (char *) malloc(strlen(RootDir)+strlen(RELEASE_SUBDIR)+1); assert(RelDir); sprintf(RelDir, "%s" RELEASE_SUBDIR, RootDir); read_datafile(); } else { read_datafile(); } } else { read_datafile(); } if( !RootDir ) { /* Try to construct RootDir from RelDir */ char *p; RootDir = malloc(strlen(RelDir)+1); strcpy(RootDir,RelDir); p = RootDir+strlen(RootDir)-1; if (p >= RootDir && (*p == '/' || *p == '\\')) --p; while (p >= RootDir && *p != '/' && *p != '\\') --p; if (p <= RootDir) { /* Empty RootDir is also an error */ exit_help("Cannot determine Root directory from " "Release directory."); } *p = '\0'; } BinDir = (char *) malloc(strlen(RootDir)+strlen(ERTS_SUBDIR_PREFIX)+ strlen(Version)+strlen(BIN_SUBDIR)+1); assert(BinDir); sprintf(BinDir, "%s" ERTS_SUBDIR_PREFIX "%s" BIN_SUBDIR, RootDir, Version); read_bootflags(); #ifdef _DEBUG fprintf(stderr, "RelDir: '%s'\n", RelDir); fprintf(stderr, "BinDir: '%s'\n", BinDir); #endif }
int main(int argc, char* argv[]) { QString logFileName; QString startupScript; bool help = false; bool vers = false; std::string theLogFileName; std::string startupScriptSource; bool panic = false; bool silent_overwrite = false; auto parser = clara::detail::Opt(help)["-h"]["--help"]("Show the help message.")| clara::detail::Opt(vers)["-v"]["--version"]("Print version.")| clara::detail::Opt(theLogFileName, "file")["-l"]("Write log to <file>.")| clara::detail::Opt(panic)["-p"]("Sets the file overwrite policy to 'panic'.")| clara::detail::Opt(silent_overwrite)["-s"]( "Sets the file overwrite policy to 'silent overwrite'.")| clara::detail::Arg(startupScriptSource, "file")("The path of the startup skript."); try { auto result = parser.parse(clara::detail::Args(argc, argv)); if (!result) { std::cerr << "Unsuported option or missing option argument.\n" << "Use '" APPLICATION_NAME " -h' for list of options\n"; exit(-1); } else if (help) exit_help(); else if (vers) exit_version(); else if (theLogFileName != "") logFileName = QString::fromStdString(theLogFileName); else if (panic) setFileOverwritePolicy(file_dialog::eFileOverwritePolicy::PANIC); else if (silent_overwrite) setFileOverwritePolicy(file_dialog::eFileOverwritePolicy::SILENT_OVERWRITE); startupScript = QString::fromStdString(startupScriptSource); } catch (std::exception const & e) { std::cerr << e.what(); exit(-1); } QApplication app(argc, argv); app.setApplicationName(APPLICATION_NAME); app.setApplicationVersion(VERSION); app.setOrganizationName(ORGANIZATION_NAME); app.setOrganizationDomain(ORGANIZATION_DOMAIN); #if defined(Q_OS_OSX) app.setStyle(QStyleFactory::create("Macintosh")); #elif defined(Q_OS_WIN) app.setStyle(QStyleFactory::create("Fusion")); #else app.setStyle(QStyleFactory::create("Fusion")); #endif if (logFileName=="") { logFileName = startupScript=="" ? qApp->applicationName() + ".log" : startupScript + ".log"; } else { if (logFileName==startupScript) { std::cerr << "Log file name coincides with startup script name\n"; exit(-1); } } std::cout << "Log file will be written to " << CSTRI(logFileName) << "\n"; Logger logger{logFileName}; Console console; QLoggingCategory::setFilterRules("*.debug=true\nqt.*.debug=false"); qInstallMessageHandler(messageHandler); Session session; new MainWin{startupScript}; // must be pointer, because it can be deleted by 'quit' trigger return app.exec(); }
/** Main program entry point from kernel. */ int main( int argc, char * const argv[] ) { n2n_sn_t sss; init_sn( &sss ); { int opt; #ifdef N2N_MULTIPLE_SUPERNODES const char *optstring = "fl:s:i:vh"; #else const char *optstring = "fl:vh"; #endif while((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) { switch (opt) { case 'l': /* local-port */ sss.lport = atoi(optarg); break; #ifdef N2N_MULTIPLE_SUPERNODES case 's': sss.sn_port = atoi(optarg); break; case 'i': { n2n_sock_t sn; sock_from_cstr(&sn, optarg); update_supernodes(&sss.supernodes, &sn); break; } #endif case 'f': /* foreground */ sss.daemon = 0; break; case 'h': /* help */ exit_help(argc, argv); break; case 'v': /* verbose */ ++traceLevel; break; } } } #if defined(N2N_HAVE_DAEMON) if (sss.daemon) { useSyslog=1; /* traceEvent output now goes to syslog. */ if ( -1 == daemon( 0, 0 ) ) { traceEvent( TRACE_ERROR, "Failed to become daemon." ); exit(-5); } } #endif /* #if defined(N2N_HAVE_DAEMON) */ traceEvent( TRACE_DEBUG, "traceLevel is %d", traceLevel); sss.sock = open_socket(sss.lport, 1 /*bind ANY*/ ); if ( -1 == sss.sock ) { traceEvent( TRACE_ERROR, "Failed to open main socket. %s", strerror(errno) ); exit(-2); } else { traceEvent( TRACE_NORMAL, "supernode is listening on UDP %u (main)", sss.lport ); } sss.mgmt_sock = open_socket(N2N_SN_MGMT_PORT, 0 /* bind LOOPBACK */ ); if ( -1 == sss.mgmt_sock ) { traceEvent( TRACE_ERROR, "Failed to open management socket. %s", strerror(errno) ); exit(-2); } else { traceEvent( TRACE_NORMAL, "supernode is listening on UDP %u (management)", N2N_SN_MGMT_PORT ); } #ifdef N2N_MULTIPLE_SUPERNODES if (load_snm_info(&sss)) { traceEvent(TRACE_ERROR, "Failed to load SNM information. %s", strerror(errno)); exit(-2); } sss.sn_sock = open_socket(sss.sn_port, 1 /* bind ANY */ ); if (-1 == sss.sn_sock) { traceEvent(TRACE_ERROR, "Failed to open supernodes communication socket. %s", strerror(errno)); exit(-2); } traceEvent(TRACE_NORMAL, "supernode is listening on UDP %u (supernodes communication)", sss.sn_port); send_req_to_all_supernodes(&sss, (sss.snm_discovery_state != N2N_SNM_STATE_READY), NULL, 0); #endif /* #ifdef N2N_MULTIPLE_SUPERNODES */ traceEvent(TRACE_NORMAL, "supernode started"); return run_loop(&sss); }
/** Hello, this is main. * \param argc Who knows. * \param argv Who knows. * \return EXIT_SUCCESS I hope. */ int main(int argc, char **argv) { char *confpath = NULL; int xfd, i, opt; ssize_t cmdlen = 1; xdgHandle xdg; bool no_argb = false; xcb_generic_event_t *event; xcb_query_tree_cookie_t tree_c; static struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "config", 1, NULL, 'c' }, { "check", 0, NULL, 'k' }, { "no-argb", 0, NULL, 'a' }, { NULL, 0, NULL, 0 } }; /* event loop watchers */ ev_io xio = { .fd = -1 }; ev_check xcheck; ev_prepare a_refresh; ev_signal sigint; ev_signal sigterm; ev_signal sighup; /* clear the globalconf structure */ p_clear(&globalconf, 1); globalconf.keygrabber = LUA_REFNIL; globalconf.mousegrabber = LUA_REFNIL; buffer_init(&globalconf.startup_errors); /* save argv */ for(i = 0; i < argc; i++) cmdlen += a_strlen(argv[i]) + 1; awesome_argv = p_new(char, cmdlen); a_strcpy(awesome_argv, cmdlen, argv[0]); for(i = 1; i < argc; i++) { a_strcat(awesome_argv, cmdlen, " "); a_strcat(awesome_argv, cmdlen, argv[i]); } /* Text won't be printed correctly otherwise */ setlocale(LC_CTYPE, ""); /* Get XDG basedir data */ xdgInitHandle(&xdg); /* init lua */ luaA_init(&xdg); /* check args */ while((opt = getopt_long(argc, argv, "vhkc:a", long_options, NULL)) != -1) switch(opt) { case 'v': eprint_version(); break; case 'h': exit_help(EXIT_SUCCESS); break; case 'k': if(!luaA_parserc(&xdg, confpath, false)) { fprintf(stderr, "✘ Configuration file syntax error.\n"); return EXIT_FAILURE; } else { fprintf(stderr, "✔ Configuration file syntax OK.\n"); return EXIT_SUCCESS; } case 'c': if(a_strlen(optarg)) confpath = a_strdup(optarg); else fatal("-c option requires a file name"); break; case 'a': no_argb = true; break; } globalconf.loop = ev_default_loop(EVFLAG_NOSIGFD); /* register function for signals */ ev_signal_init(&sigint, exit_on_signal, SIGINT); ev_signal_init(&sigterm, exit_on_signal, SIGTERM); ev_signal_init(&sighup, restart_on_signal, SIGHUP); ev_signal_start(globalconf.loop, &sigint); ev_signal_start(globalconf.loop, &sigterm); ev_signal_start(globalconf.loop, &sighup); ev_unref(globalconf.loop); ev_unref(globalconf.loop); ev_unref(globalconf.loop); struct sigaction sa = { .sa_handler = signal_fatal, .sa_flags = 0 }; sigemptyset(&sa.sa_mask); sigaction(SIGSEGV, &sa, 0); /* X stuff */ globalconf.connection = xcb_connect(NULL, &globalconf.default_screen); if(xcb_connection_has_error(globalconf.connection)) fatal("cannot open display"); globalconf.screen = xcb_aux_get_screen(globalconf.connection, globalconf.default_screen); /* FIXME The following two assignments were swapped on purpose */ if(!no_argb) globalconf.visual = a_default_visual(globalconf.screen); if(!globalconf.visual) globalconf.visual = a_argb_visual(globalconf.screen); globalconf.default_depth = a_visual_depth(globalconf.screen, globalconf.visual->visual_id); globalconf.default_cmap = globalconf.screen->default_colormap; if(globalconf.default_depth != globalconf.screen->root_depth) { // We need our own color map if we aren't using the default depth globalconf.default_cmap = xcb_generate_id(globalconf.connection); xcb_create_colormap(globalconf.connection, XCB_COLORMAP_ALLOC_NONE, globalconf.default_cmap, globalconf.screen->root, globalconf.visual->visual_id); } /* Prefetch all the extensions we might need */ xcb_prefetch_extension_data(globalconf.connection, &xcb_big_requests_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_test_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_randr_id); xcb_prefetch_extension_data(globalconf.connection, &xcb_xinerama_id); /* initialize dbus */ a_dbus_init(); /* Get the file descriptor corresponding to the X connection */ xfd = xcb_get_file_descriptor(globalconf.connection); ev_io_init(&xio, &a_xcb_io_cb, xfd, EV_READ); ev_io_start(globalconf.loop, &xio); ev_check_init(&xcheck, &a_xcb_check_cb); ev_check_start(globalconf.loop, &xcheck); ev_unref(globalconf.loop); ev_prepare_init(&a_refresh, &a_refresh_cb); ev_prepare_start(globalconf.loop, &a_refresh); ev_unref(globalconf.loop); /* Grab server */ xcb_grab_server(globalconf.connection); /* Make sure there are no pending events. Since we didn't really do anything * at all yet, we will just discard all events which we received so far. * The above GrabServer should make sure no new events are generated. */ xcb_aux_sync(globalconf.connection); while ((event = xcb_poll_for_event(globalconf.connection)) != NULL) { /* Make sure errors are printed */ uint8_t response_type = XCB_EVENT_RESPONSE_TYPE(event); if(response_type == 0) event_handle(event); p_delete(&event); } { const uint32_t select_input_val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT; /* This causes an error if some other window manager is running */ xcb_change_window_attributes(globalconf.connection, globalconf.screen->root, XCB_CW_EVENT_MASK, &select_input_val); } /* Need to xcb_flush to validate error handler */ xcb_aux_sync(globalconf.connection); /* Process all errors in the queue if any. There can be no events yet, so if * this function returns something, it must be an error. */ if (xcb_poll_for_event(globalconf.connection) != NULL) fatal("another window manager is already running"); /* Prefetch the maximum request length */ xcb_prefetch_maximum_request_length(globalconf.connection); /* check for xtest extension */ const xcb_query_extension_reply_t *xtest_query; xtest_query = xcb_get_extension_data(globalconf.connection, &xcb_test_id); globalconf.have_xtest = xtest_query->present; /* Allocate the key symbols */ globalconf.keysyms = xcb_key_symbols_alloc(globalconf.connection); xcb_get_modifier_mapping_cookie_t xmapping_cookie = xcb_get_modifier_mapping_unchecked(globalconf.connection); /* init atom cache */ atoms_init(globalconf.connection); /* init screens information */ screen_scan(); xutil_lock_mask_get(globalconf.connection, xmapping_cookie, globalconf.keysyms, &globalconf.numlockmask, &globalconf.shiftlockmask, &globalconf.capslockmask, &globalconf.modeswitchmask); /* do this only for real screen */ ewmh_init(); systray_init(); /* init spawn (sn) */ spawn_init(); /* The default GC is just a newly created associated with a window with * depth globalconf.default_depth */ xcb_window_t tmp_win = xcb_generate_id(globalconf.connection); globalconf.gc = xcb_generate_id(globalconf.connection); xcb_create_window(globalconf.connection, globalconf.default_depth, tmp_win, globalconf.screen->root, -1, -1, 1, 1, 0, XCB_COPY_FROM_PARENT, globalconf.visual->visual_id, XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL | XCB_CW_COLORMAP, (const uint32_t []) { globalconf.screen->black_pixel, globalconf.screen->black_pixel, globalconf.default_cmap }); xcb_create_gc(globalconf.connection, globalconf.gc, tmp_win, XCB_GC_FOREGROUND | XCB_GC_BACKGROUND, (const uint32_t[]) { globalconf.screen->black_pixel, globalconf.screen->white_pixel }); xcb_destroy_window(globalconf.connection, tmp_win); /* Get the window tree associated to this screen */ tree_c = xcb_query_tree_unchecked(globalconf.connection, globalconf.screen->root); xcb_change_window_attributes(globalconf.connection, globalconf.screen->root, XCB_CW_EVENT_MASK, ROOT_WINDOW_EVENT_MASK); /* we will receive events, stop grabbing server */ xcb_ungrab_server(globalconf.connection); /* Parse and run configuration file */ if (!luaA_parserc(&xdg, confpath, true)) fatal("couldn't find any rc file"); p_delete(&confpath); xdgWipeHandle(&xdg); /* scan existing windows */ scan(tree_c); xcb_flush(globalconf.connection); /* main event loop */ ev_loop(globalconf.loop, 0); /* cleanup event loop */ ev_ref(globalconf.loop); ev_check_stop(globalconf.loop, &xcheck); ev_ref(globalconf.loop); ev_prepare_stop(globalconf.loop, &a_refresh); ev_ref(globalconf.loop); ev_io_stop(globalconf.loop, &xio); awesome_atexit(false); return EXIT_SUCCESS; }