コード例 #1
0
ファイル: rdm.cpp プロジェクト: LuXuryPro/rtags
int main(int argc, char** argv)
{
#ifdef OS_Darwin
    struct rlimit rlp;
    if (getrlimit(RLIMIT_NOFILE, &rlp) == 0) {
        if (rlp.rlim_cur < 1000) {
            rlp.rlim_cur = 1000;
            setrlimit(RLIMIT_NOFILE, &rlp);
        }
    }
#endif

    {
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_getstacksize(&attr, &defaultStackSize);
        pthread_attr_destroy(&attr);
        if (defaultStackSize < 1024 * 1024 * 4) { // 4 megs should be enough for everyone right?
            defaultStackSize = 1024 * 1024 * 4;
        }
    }

    Rct::findExecutablePath(*argv);

    struct option opts[] = {
        { "help", no_argument, 0, 'h' },
        { "version", no_argument, 0, 2 },
        { "include-path", required_argument, 0, 'I' },
        { "isystem", required_argument, 0, 's' },
        { "define", required_argument, 0, 'D' },
        { "log-file", required_argument, 0, 'L' },
        { "setenv", required_argument, 0, 'e' },
        { "no-Wall", no_argument, 0, 'W' },
        { "Weverything", no_argument, 0, 'u' },
        { "cache-AST", required_argument, 0, 'A' },
        { "verbose", no_argument, 0, 'v' },
        { "job-count", required_argument, 0, 'j' },
        { "header-error-job-count", required_argument, 0, 'H' },
        { "test", required_argument, 0, 't' },
        { "test-timeout", required_argument, 0, 'z' },
        { "clean-slate", no_argument, 0, 'C' },
        { "disable-sighandler", no_argument, 0, 'x' },
        { "silent", no_argument, 0, 'S' },
        { "exclude-filter", required_argument, 0, 'X' },
        { "socket-file", required_argument, 0, 'n' },
        { "config", required_argument, 0, 'c' },
        { "no-rc", no_argument, 0, 'N' },
        { "data-dir", required_argument, 0, 'd' },
        { "ignore-printf-fixits", no_argument, 0, 'F' },
        { "no-unlimited-errors", no_argument, 0, 'f' },
        { "block-argument", required_argument, 0, 'G' },
        { "no-spell-checking", no_argument, 0, 'l' },
        { "large-by-value-copy", required_argument, 0, 'r' },
        { "disallow-multiple-sources", no_argument, 0, 'm' },
        { "no-startup-project", no_argument, 0, 'o' },
        { "no-no-unknown-warnings-option", no_argument, 0, 'Y' },
        { "ignore-compiler", required_argument, 0, 'b' },
        { "watch-system-paths", no_argument, 0, 'w' },
        { "rp-visit-file-timeout", required_argument, 0, 'Z' },
        { "rp-indexer-message-timeout", required_argument, 0, 'T' },
        { "rp-connect-timeout", required_argument, 0, 'O' },
        { "rp-connect-attempts", required_argument, 0, 3 },
        { "rp-nice-value", required_argument, 0, 'a' },
        { "thread-stack-size", required_argument, 0, 'k' },
        { "suspend-rp-on-crash", no_argument, 0, 'q' },
        { "rp-log-to-syslog", no_argument, 0, 7 },
        { "start-suspended", no_argument, 0, 'Q' },
        { "separate-debug-and-release", no_argument, 0, 'E' },
        { "max-crash-count", required_argument, 0, 'K' },
        { "completion-cache-size", required_argument, 0, 'i' },
        { "completion-no-filter", no_argument, 0, 8 },
        { "extra-compilers", required_argument, 0, 'U' },
        { "allow-Wpedantic", no_argument, 0, 'P' },
        { "enable-compiler-manager", no_argument, 0, 'R' },
        { "enable-NDEBUG", no_argument, 0, 'g' },
        { "progress", no_argument, 0, 'p' },
        { "max-file-map-cache-size", required_argument, 0, 'y' },
#ifdef OS_FreeBSD
        { "filemanager-watch", no_argument, 0, 'M' },
#else
        { "no-filemanager-watch", no_argument, 0, 'M' },
#endif
        { "no-filemanager", no_argument, 0, 15 },
        { "no-file-lock", no_argument, 0, 13 },
        { "pch-enabled", no_argument, 0, 14 },
        { "no-filesystem-watcher", no_argument, 0, 'B' },
        { "arg-transform", required_argument, 0, 'V' },
        { "no-comments", no_argument, 0, 1 },
#ifdef RTAGS_HAS_LAUNCHD
        { "launchd", no_argument, 0, 4 },
#endif
        { "inactivity-timeout", required_argument, 0, 5 },
        { "daemon", no_argument, 0, 6 },
        { "log-file-log-level", required_argument, 0, 9 },
        { "watch-sources-only", no_argument, 0, 10 },
        { "debug-locations", no_argument, 0, 11 },
        { "validate-file-maps", no_argument, 0, 16 },
        { "tcp-port", required_argument, 0, 12 },
        { "rp-path", required_argument, 0, 17 },
        { "log-timestamp", no_argument, 0, 18 },
        { 0, 0, 0, 0 }
    };
    const String shortOptions = Rct::shortOptions(opts);
    if (getenv("RTAGS_DUMP_UNUSED")) {
        String unused;
        for (int i=0; i<26; ++i) {
            if (!shortOptions.contains('a' + i))
                unused.append('a' + i);
            if (!shortOptions.contains('A' + i))
                unused.append('A' + i);
        }
        printf("Unused: %s\n", unused.constData());
        for (int i=0; opts[i].name; ++i) {
            if (opts[i].name) {
                if (!opts[i].val) {
                    printf("No shortoption for %s\n", opts[i].name);
                } else if (opts[i].name[0] != opts[i].val) {
                    printf("Not ideal option for %s|%c\n", opts[i].name, opts[i].val);
                }
            }
        }
        return 0;
    }

    bool daemon = false;
    List<String> argCopy;
    List<char*> argList;
    {
        bool norc = false;
        Path rcfile = Path::home() + ".rdmrc";
        opterr = 0;

        StackBuffer<128, char*> originalArgv(argc);
        memcpy(originalArgv, argv, sizeof(char*) * argc);
        /* getopt will molest argv by moving pointers around when it sees
         * fit. Their idea of an optional argument is different from ours so we
         * have to take a copy of argv before they get their sticky fingers all
         * over it.
         *
         * We think this should be okay for an optional argument:
         * -s something
         *
         * They only populate optarg if you do:
         * -ssomething.
         *
         * We don't want to copy argv into argList before processing rc files
         * since command line args should take precedence over things in rc
         * files.
         *
         */

        while (true) {
            const int c = getopt_long(argc, argv, shortOptions.constData(), opts, 0);
            if (c == -1)
                break;
            switch (c) {
            case 'N':
                norc = true;
                break;
            case 'c':
                rcfile = optarg;
                break;
            default:
                break;
            }
        }
        opterr = 1;
        argList.append(argv[0]);
        if (!norc) {
            String rc = Path("/etc/rdmrc").readAll();
            if (!rc.isEmpty()) {
                for (const String& s : rc.split('\n')) {
                    if (!s.isEmpty() && !s.startsWith('#'))
                        argCopy += s.split(' ');
                }
            }
            if (!rcfile.isEmpty()) {
                rc = rcfile.readAll();
                if (!rc.isEmpty()) {
                    for (const String& s : rc.split('\n')) {
                        if (!s.isEmpty() && !s.startsWith('#'))
                            argCopy += s.split(' ');
                    }
                }
            }
            const int s = argCopy.size();
            for (int i=0; i<s; ++i) {
                String &arg = argCopy.at(i);
                if (!arg.isEmpty())
                    argList.append(arg.data());
            }
        }

        for (int i=1; i<argc; ++i)
            argList.append(originalArgv[i]);

        optind = 1;
    }

    Server::Options serverOpts;
    serverOpts.threadStackSize = defaultStackSize;
    serverOpts.socketFile = String::format<128>("%s.rdm", Path::home().constData());
    serverOpts.jobCount = std::max(2, ThreadPool::idealThreadCount());
    serverOpts.headerErrorJobCount = -1;
    serverOpts.rpVisitFileTimeout = DEFAULT_RP_VISITFILE_TIMEOUT;
    serverOpts.rpIndexDataMessageTimeout = DEFAULT_RP_INDEXER_MESSAGE_TIMEOUT;
    serverOpts.rpConnectTimeout = DEFAULT_RP_CONNECT_TIMEOUT;
    serverOpts.rpConnectAttempts = DEFAULT_RP_CONNECT_ATTEMPTS;
    serverOpts.maxFileMapScopeCacheSize = DEFAULT_RDM_MAX_FILE_MAP_CACHE_SIZE;
    serverOpts.rpNiceValue = INT_MIN;
    serverOpts.options = Server::Wall|Server::SpellChecking;
    serverOpts.maxCrashCount = DEFAULT_MAX_CRASH_COUNT;
    serverOpts.completionCacheSize = DEFAULT_COMPLETION_CACHE_SIZE;
    serverOpts.rp = defaultRP();
#ifdef OS_FreeBSD
    serverOpts.options |= Server::NoFileManagerWatch;
#endif
// #ifndef NDEBUG
//     serverOpts.options |= Server::SuspendRPOnCrash;
// #endif
    serverOpts.dataDir = String::format<128>("%s.rtags", Path::home().constData());

    const char *logFile = 0;
    Flags<LogFlag> logFlags = DontRotate|LogStderr;
    LogLevel logLevel(LogLevel::Error);
    LogLevel logFileLogLevel(LogLevel::Error);
    bool sigHandler = true;
    assert(Path::home().endsWith('/'));
    int argCount = argList.size();
    char **args = argList.data();
    bool defaultDataDir = true;
    int inactivityTimeout = 0;

    while (true) {
        const int c = getopt_long(argCount, args, shortOptions.constData(), opts, 0);
        if (c == -1)
            break;
        switch (c) {
        case 'N':
        case 'c':
            // ignored
            break;
        case 'S':
            logLevel = LogLevel::None;
            break;
        case 'X':
            serverOpts.excludeFilters += String(optarg).split(';');
            break;
        case 'G':
            serverOpts.blockedArguments << optarg;
            break;
        case 1:
            serverOpts.options |= Server::NoComments;
            break;
        case 10:
            serverOpts.options |= Server::WatchSourcesOnly;
            break;
        case 11:
            if (!strcmp(optarg, "clear") || !strcmp(optarg, "none")) {
                serverOpts.debugLocations.clear();
            } else {
                serverOpts.debugLocations << optarg;
            }
            break;
        case 12:
            serverOpts.tcpPort = atoi(optarg);
            if (!serverOpts.tcpPort) {
                fprintf(stderr, "Invalid port %s for --tcp-port\n", optarg);
                return 1;
            }
            break;
        case 13:
            serverOpts.options |= Server::NoFileLock;
            break;
        case 14:
            serverOpts.options |= Server::PCHEnabled;
            break;
        case 15:
            serverOpts.options |= Server::NoFileManager;
            break;
        case 16:
            serverOpts.options |= Server::ValidateFileMaps;
            break;
        case 17:
            serverOpts.rp = optarg;
            if (serverOpts.rp.isFile())
                serverOpts.rp.resolve();
            break;
        case 18:
            logFlags |= LogTimeStamp;
            break;
        case 2:
            fprintf(stdout, "%s\n", RTags::versionString().constData());
            return 0;
        case 6:
            daemon = true;
            logLevel = LogLevel::None;
            break;
        case 9:
            if (!strcasecmp(optarg, "verbose-debug")) {
                logFileLogLevel = LogLevel::VerboseDebug;
            } else if (!strcasecmp(optarg, "debug")) {
                logFileLogLevel = LogLevel::Debug;
            } else if (!strcasecmp(optarg, "warning")) {
                logFileLogLevel = LogLevel::Warning;
            } else if (!strcasecmp(optarg, "error")) {
                logFileLogLevel = LogLevel::Error;
            } else {
                fprintf(stderr, "Unknown log level: %s options are error, warning, debug or verbose-debug\n",
                        optarg);
                return 1;
            }
            break;
        case 'U':
            serverOpts.extraCompilers.append(std::regex(optarg));
            break;
        case 'E':
            serverOpts.options |= Server::SeparateDebugAndRelease;
            break;
        case 'g':
            serverOpts.options |= Server::EnableNDEBUG;
            break;
        case 'Q':
            serverOpts.options |= Server::StartSuspended;
            break;
        case 'Z':
            serverOpts.rpVisitFileTimeout = atoi(optarg);
            if (serverOpts.rpVisitFileTimeout < 0) {
                fprintf(stderr, "Invalid argument to -Z %s\n", optarg);
                return 1;
            }
            if (!serverOpts.rpVisitFileTimeout)
                serverOpts.rpVisitFileTimeout = -1;
            break;
        case 'y':
            serverOpts.maxFileMapScopeCacheSize = atoi(optarg);
            if (serverOpts.maxFileMapScopeCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -y %s\n", optarg);
                return 1;
            }
            break;
        case 'O':
            serverOpts.rpConnectTimeout = atoi(optarg);
            if (serverOpts.rpConnectTimeout < 0) {
                fprintf(stderr, "Invalid argument to -O %s\n", optarg);
                return 1;
            }
            break;
        case 3:
            serverOpts.rpConnectAttempts = atoi(optarg);
            if (serverOpts.rpConnectAttempts <= 0) {
                fprintf(stderr, "Invalid argument to --rp-connect-attempts %s\n", optarg);
                return 1;
            }
            break;
        case 'k':
            serverOpts.threadStackSize = atoi(optarg);
            if (serverOpts.threadStackSize < 0) {
                fprintf(stderr, "Invalid argument to -k %s\n", optarg);
                return 1;
            }
            break;
        case 'b':
            serverOpts.ignoredCompilers.insert(Path::resolved(optarg));
            break;
        case 't': {
            Path test(optarg);
            if (!test.resolve() || !test.isFile()) {
                fprintf(stderr, "%s doesn't seem to be a file\n", optarg);
                return 1;
            }
            serverOpts.tests += test;
            break; }
        case 'z':
            serverOpts.testTimeout = atoi(optarg);
            if (serverOpts.testTimeout <= 0) {
                fprintf(stderr, "Invalid argument to -z %s\n", optarg);
                return 1;
            }
            break;
        case 'n':
            serverOpts.socketFile = optarg;
            break;
        case 'd':
            defaultDataDir = false;
            serverOpts.dataDir = String::format<128>("%s", Path::resolved(optarg).constData());
            break;
        case 'h':
            usage(stdout);
            return 0;
        case 'Y':
            serverOpts.options |= Server::NoNoUnknownWarningsOption;
            break;
        case 'p':
            serverOpts.options |= Server::Progress;
            break;
        case 'R':
            serverOpts.options |= Server::EnableCompilerManager;
            break;
        case 'm':
            serverOpts.options |= Server::DisallowMultipleSources;
            break;
        case 'o':
            serverOpts.options |= Server::NoStartupCurrentProject;
            break;
        case 'w':
            serverOpts.options |= Server::WatchSystemPaths;
            break;
        case 'q':
            serverOpts.options |= Server::SuspendRPOnCrash;
            break;
        case 'M':
#ifdef OS_FreeBSD
            serverOpts.options &= ~Server::NoFileManagerWatch;
#else
            serverOpts.options |= Server::NoFileManagerWatch;
#endif
            break;
        case 'B':
            serverOpts.options |= Server::NoFileSystemWatch;
            break;
        case 'V':
            serverOpts.argTransform = Process::findCommand(optarg);
            if (strlen(optarg) && serverOpts.argTransform.isEmpty()) {
                fprintf(stderr, "Invalid argument to -V. Can't resolve %s", optarg);
                return 1;
            }

            break;
      case 'F':
            serverOpts.options |= Server::IgnorePrintfFixits;
            break;
        case 'f':
            serverOpts.options |= Server::NoUnlimitedErrors;
            break;
        case 'l':
            serverOpts.options &= ~Server::SpellChecking;
            break;
        case 'W':
            serverOpts.options &= ~Server::Wall;
            break;
        case 'u':
            serverOpts.options |= Server::Weverything;
            break;
        case 'P':
            serverOpts.options |= Server::AllowPedantic;
            break;
        case 'C':
            serverOpts.options |= Server::ClearProjects;
            break;
        case 'e':
            putenv(optarg);
            break;
        case 'x':
            sigHandler = false;
            break;
        case 'K':
            serverOpts.maxCrashCount = atoi(optarg);
            if (serverOpts.maxCrashCount <= 0) {
                fprintf(stderr, "Invalid argument to -K %s\n", optarg);
                return 1;
            }
            break;
        case 'i':
            serverOpts.completionCacheSize = atoi(optarg);
            if (serverOpts.completionCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -i %s\n", optarg);
                return 1;
            }
            break;
        case 'T':
            serverOpts.rpIndexDataMessageTimeout = atoi(optarg);
            if (serverOpts.rpIndexDataMessageTimeout <= 0) {
                fprintf(stderr, "Can't parse argument to -T %s.\n", optarg);
                return 1;
            }
            break;
        case 'a': {
            bool ok;
            serverOpts.rpNiceValue = String(optarg).toLong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -a %s.\n", optarg);
                return 1;
            }
            break; }
        case 'j': {
            bool ok;
            serverOpts.jobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -j %s. -j must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'H': {
            bool ok;
            serverOpts.headerErrorJobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -H %s. -H must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'r': {
            int large = atoi(optarg);
            if (large <= 0) {
                fprintf(stderr, "Can't parse argument to -r %s\n", optarg);
                return 1;
            }
            serverOpts.defaultArguments.append("-Wlarge-by-value-copy=" + String(optarg)); // ### not quite working
            break; }
        case 'D': {
            const char *eq = strchr(optarg, '=');
            Source::Define def;
            if (!eq) {
                def.define = optarg;
            } else {
                def.define = String(optarg, eq - optarg);
                def.value = eq + 1;
            }
            serverOpts.defines.append(def);
            break; }
        case 'I':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_Include, Path::resolved(optarg)));
            break;
        case 's':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_System, Path::resolved(optarg)));
            break;
        case 'L':
            logFile = optarg;
            logLevel = LogLevel::None;
            break;
        case 'v':
            if (logLevel != LogLevel::None)
                ++logLevel;
            break;
#ifdef RTAGS_HAS_LAUNCHD
        case 4:
            serverOpts.options |= Server::Launchd;
            break;
#endif
        case 5:
            inactivityTimeout = atoi(optarg); // seconds.
            if (inactivityTimeout <= 0) {
                fprintf(stderr, "Invalid argument to --inactivity-timeout %s\n", optarg);
                return 1;
            }
            break;
        case 7:
            serverOpts.options |= Server::RPLogToSyslog;
            break;
        case 8:
            serverOpts.options |= Server::CompletionsNoFilter;
            break;
        case '?': {
            fprintf(stderr, "Run rdm --help for help\n");
            return 1; }
        }
    }
    if (optind < argCount) {
        fprintf(stderr, "rdm: unexpected option -- '%s'\n", args[optind]);
        return 1;
    }

    if (daemon) {
        switch (fork()) {
        case -1:
            fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
            return 1;
        case 0:
            setsid();
            switch (fork()) {
            case -1:
                fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
                return 1;
            case 0:
                break;
            default:
                return 0;
            }
            break;
        default:
            return 0;
        }
    }

    if (serverOpts.excludeFilters.isEmpty())
        serverOpts.excludeFilters = String(EXCLUDEFILTER_DEFAULT).split(';');

    if (!serverOpts.headerErrorJobCount) {
        serverOpts.headerErrorJobCount = std::max<size_t>(1, serverOpts.jobCount / 2);
    } else {
        serverOpts.headerErrorJobCount = std::min(serverOpts.headerErrorJobCount, serverOpts.jobCount);
    }

    if (sigHandler) {
        signal(SIGSEGV, sigSegvHandler);
        signal(SIGILL, sigSegvHandler);
        signal(SIGABRT, sigSegvHandler);
    }

    // Shell-expand logFile
    Path logPath(logFile); logPath.resolve();

    if (!initLogging(argv[0], logFlags, logLevel, logPath.constData(), logFileLogLevel)) {
        fprintf(stderr, "Can't initialize logging with %d %s %s\n",
                logLevel.toInt(), logFile ? logFile : "", logFlags.toString().constData());
        return 1;
    }

#ifdef RTAGS_HAS_LAUNCHD
    if (serverOpts.options & Server::Launchd) {
        // Clamp inactivity timeout. launchd starts to worry if the
        // process runs for less than 10 seconds.

        static const int MIN_INACTIVITY_TIMEOUT = 15; // includes
                                                      // fudge factor.

        if (inactivityTimeout < MIN_INACTIVITY_TIMEOUT) {
            inactivityTimeout = MIN_INACTIVITY_TIMEOUT;
            fprintf(stderr, "launchd mode - clamped inactivity timeout to %d to avoid launchd warnings.\n", inactivityTimeout);
        }
    }
#endif

    EventLoop::SharedPtr loop(new EventLoop);
    loop->init(EventLoop::MainEventLoop|EventLoop::EnableSigIntHandler|EventLoop::EnableSigTermHandler);

    std::shared_ptr<Server> server(new Server);
    if (!serverOpts.tests.isEmpty()) {
        char buf[1024];
        Path path;
        while (true) {
            strcpy(buf, "/tmp/rtags-test-XXXXXX");
            if (!mkdtemp(buf)) {
                fprintf(stderr, "Failed to mkdtemp (%d)\n", errno);
                return 1;
            }
            path = buf;
            path.resolve();
            break;
        }
        serverOpts.dataDir = path;
        strcpy(buf, "/tmp/rtags-sock-XXXXXX");
        const int fd = mkstemp(buf);
        if (fd == -1) {
            fprintf(stderr, "Failed to mkstemp (%d)\n", errno);
            return 1;
        }
        close(fd);
        serverOpts.socketFile = buf;
        serverOpts.socketFile.resolve();
    }
    if (defaultDataDir) {
        Path migration = String::format<128>("%s.rtags-file", Path::home().constData());
        if (migration.isDir()) {
            Rct::removeDirectory(serverOpts.dataDir);
            rename(migration.constData(), serverOpts.dataDir.constData());
            error() << "Migrated datadir from ~/.rtags-file ~/.rtags";
        }
    }
    serverOpts.dataDir = serverOpts.dataDir.ensureTrailingSlash();
    if (!server->init(serverOpts)) {
        cleanupLogging();
        return 1;
    }

    if (!serverOpts.tests.isEmpty()) {
        return server->runTests() ? 0 : 1;
    }

    loop->setInactivityTimeout(inactivityTimeout * 1000);

    loop->exec();
    const int ret = server->exitCode();
    server.reset();
    cleanupLogging();
    return ret;
}
コード例 #2
0
int main() {
    
    char *customData = getCustomRecordedGameData();

    initDrawString( w, h );
    
    initFrameDrawer( w, h, 60,
                     customData, false );
    
    delete [] customData;
    

    initSimulator();
    
    int port = 
        SettingsManager::getIntSetting( "simulatorServerPort", 5077 );

    char *password = 
        SettingsManager::getStringSetting( "simulatorServerPassword" );
    
    if( password == NULL ) {
        password = stringDuplicate( "secret" );
        }
    

    
    SocketServer server( port, 256 );

    char quit = false;
    
    while( !quit ) {
        printf( "Waiting for connection on port %d, password = '%s'\n", 
                port, password );

        Socket *sock = server.acceptConnection();
        
        if( sock != NULL ) {
            printf( "Got connection\n" );

            char *request = readFullRequest( sock );
            
            if( request != NULL ) {

                char *response = NULL;

                if( strstr( request, "quit" ) == request ) {
                    // starts with quit
                
                    if( strstr( request, password ) != NULL ) {
                        quit = true;
                    
                        response = stringDuplicate( "OK" );
                        }
                    else {
                        response = stringDuplicate( "FAILED" );
                        }
                    }
                else if( strstr( request, "check_alive" ) == request ) {
                    response = stringDuplicate( "OK" );
                    }
                else if( strstr( request, "simulate_robbery" ) == request ) {
                    double startTime = Time::getCurrentTime();
                
                    response = simulateRobbery( request );
                    
                    double netTime = Time::getCurrentTime() - startTime;
                    printf( "Simulation took %f seconds\n", netTime );
                    }
                else {
                    response = stringDuplicate( "FAILED" );
                    }
            

                delete [] request;
            
                sock->send( (unsigned char *)response, strlen( response ), 
                            true, false );
            
                delete [] response;


                sock->send( (unsigned char *)"\n", strlen( "\n" ), 
                            true, false );


                sock->send( (unsigned char *)END_RESPONSE, 
                            strlen( END_RESPONSE ), 
                            true, false );


                sock->sendFlushBeforeClose( 3000 );
                }
            
            delete sock;
            }
        }
    
    delete [] password;
    
    freeSimulator();
    
    freeDrawString();
    freeFrameDrawer();
    }
void TestThemeDaemonServerThread::run()
{
    TestThemeDaemonServer server(m_serverAddress, m_pixmapCache);
    exec();
}
コード例 #4
0
ファイル: main.cpp プロジェクト: wolves3d/RoomControl
int main()
{
	CServer server(SERVER_PORT);

	// -------------------------------------------------------------------------

	printf("--- Client ---\n");
	CClient client;
	client.Init("127.0.0.1", SERVER_PORT);

	// -------------------------------------------------------------------------

	//	uint logDelay = 1000 * 60 * 30;
	uint logDelay = 5;
	time_t deadline = 0;
	bool readFlag = false;

	/*
	byte args[] = { 0, 8, 0, 1, 2, 3, 4, 5, 6, 7 };
	g_commMgr->PushCommand(CMD_WRITE_EEPROM, &args, sizeof(args));
	*/

//	arduinoCmdManager.SendCommand(&arduinoPort, CMD_REQUEST_ONE_WIRE_ENUM, NULL, 0);
	
	while (true)
	{
		server.OnUpdate();
		client.OnUpdate();
		
		System::SleepMS(0);
		/*
		if (false == readFlag)
		{
			if (true == device->IsOneWireEnumerated())
			{
				//OnEnumerationDone();
				readFlag = true;

				// test "turn on relay"
				//byte data[] = { 4, 0 };
				//arduinoCmdManager.SendCommand(&arduinoPort, CMD_PIN_WRITE, &data, sizeof(data));
			}
		}

		if (true == readFlag)
		{
			const time_t currentTime = time(NULL);
			if (currentTime >= deadline)
			{
				deadline = (currentTime + logDelay);
				OneWireAddr addr = device->GetOneWireDevice(0);

				arduinoCmdManager.SendCommand(
					&arduinoPort,
					CMD_OW_READ_TEMP_SENSOR_DATA,
					addr.Address(),
					OneWireAddr::ADDR_LEN);
			}
		}
		*/
	}

//	comPort.Close();
	return 0;
}
コード例 #5
0
ファイル: compress.cpp プロジェクト: hiwang123/x0
	~compress_plugin() {
		server().onPostProcess.disconnect(postProcess_);
	}
コード例 #6
0
ファイル: test_base.cpp プロジェクト: hungld/elliptics
nodes_data::ptr start_nodes(std::ostream &debug_stream, const std::vector<config_data> &configs, const std::string &path)
{
	nodes_data::ptr data = std::make_shared<nodes_data>();

	std::string base_path;
	std::string auth_cookie;
	std::string cocaine_config_template = read_file(COCAINE_CONFIG_PATH);
	std::string run_path;

	{
		char buffer[1024];

		snprintf(buffer, sizeof(buffer), "%04x%04x", rand(), rand());
		buffer[sizeof(buffer) - 1] = 0;
		auth_cookie = buffer;

		snprintf(buffer, sizeof(buffer), "/tmp/elliptics-test-run-%04x/", rand());
		buffer[sizeof(buffer) - 1] = 0;
		run_path = buffer;
	}

	const auto ports = generate_ports(configs.size());

	if (path.empty()) {
		char buffer[1024];

		snprintf(buffer, sizeof(buffer), "/tmp/elliptics-test-%04x/", rand());
		buffer[sizeof(buffer) - 1] = 0;
		base_path = buffer;

		create_directory(base_path);
		data->directory = directory_handler(base_path, true);
	} else {
		base_path = path;

		create_directory(base_path);
		data->directory = directory_handler(base_path, false);
	}

	debug_stream << "Set base directory: \"" << base_path << "\"" << std::endl;

	create_directory(run_path);
	data->run_directory = directory_handler(run_path, true);
	debug_stream << "Set cocaine run directory: \"" << run_path << "\"" << std::endl;

	std::string cocaine_remotes;
	for (size_t j = 0; j < configs.size(); ++j) {
		if (j > 0)
			cocaine_remotes += ", ";
		cocaine_remotes += "\"localhost\": " + ports[j];
	}

	const auto cocaine_locator_ports = generate_ports(configs.size());
	// client only needs connection to one (any) locator service
	data->locator_port = std::stoul(cocaine_locator_ports[0]);

	debug_stream << "Starting " << configs.size() << " servers" << std::endl;

	for (size_t i = 0; i < configs.size(); ++i) {
		debug_stream << "Starting server #" << (i + 1) << std::endl;

		const std::string server_path = base_path + "/server-" + boost::lexical_cast<std::string>(i + 1);

		create_directory(server_path);
		create_directory(server_path + "/blob");
		create_directory(server_path + "/history");

		std::string remotes;
		for (size_t j = 0; j < configs.size(); ++j) {
			if (j == i)
				continue;

			remotes += create_remote(ports[j]);
		}

		config_data config = configs[i];
		if (remotes.empty())
			config("remote", NULL_VALUE);
		else
			config("remote", remotes);

		if (config.has_value("srw_config")) {
			create_directory(server_path + "/run");

			const substitute_context cocaine_variables = {
				{ "COCAINE_LOCATOR_PORT", cocaine_locator_ports[i] },
				{ "COCAINE_PLUGINS_PATH", COCAINE_PLUGINS_PATH },
				{ "ELLIPTICS_REMOTES", cocaine_remotes },
				{ "ELLIPTICS_GROUPS", "1" },
				{ "COCAINE_LOG_PATH", server_path + "/cocaine.log" },
				{ "COCAINE_RUN_PATH", run_path }
			};
			create_cocaine_config(server_path + "/cocaine.conf", cocaine_config_template, cocaine_variables);

			config("srw_config", server_path + "/cocaine.conf");
		}

		create_config(config, server_path + "/ioserv.conf")
				("auth_cookie", auth_cookie)
				("log", server_path + "/log.log")
				("addr", create_remote(ports[i]))
				("history", server_path + "/history")
				("data", server_path + "/blob/data")
				;

		server_node server(server_path + "/ioserv.conf", create_remote(ports[i]));

		server.start();
		debug_stream << "Started server #" << (i + 1) << std::endl;

		data->nodes.emplace_back(std::move(server));
	}

	{
		std::vector<std::string> remotes;
		for (size_t i = 0; i < data->nodes.size(); ++i) {
			remotes.push_back(data->nodes[i].remote());
		}

		start_client_nodes(data, debug_stream, remotes);
	}

	return data;
}
コード例 #7
0
ファイル: XBLive_MM.cpp プロジェクト: 3ddy/Jedi-Academy
// Search for and join a good online server
// GameType is optional - X_MATCH_NULL_INTEGER to omit
bool XBL_MM_QuickMatch(ULONGLONG GameType)
{
	// Reuse our optimatch query object. VVFIXME - needs to be torn down first?

	HRESULT hr = query.Query(
		GameType,
		X_MATCH_NULL_INTEGER,		// CurrentMap
		0,							// MinimumPlayers
		8,							// MaximumPlayers
		X_MATCH_NULL_INTEGER,		// FriendlyFire
		X_MATCH_NULL_INTEGER,		// JediMastery
		X_MATCH_NULL_INTEGER,		// SaberOnly
		X_MATCH_NULL_INTEGER);		// Dedicated
	if ( FAILED( hr ) )
	{
		UI_xboxErrorPopup( XB_POPUP_MATCHMAKING_ERROR );
		return false;
	}
	// Keep servicing the query until it completes.
	// The logon task must also be serviced in order to remain connected. 
	do
	{
		if( !XBL_PumpLogon() )
			return false;
		hr = query.Process();
	} while( query.IsRunning() );

	if( !query.Succeeded() )
	{
		UI_xboxErrorPopup( XB_POPUP_MATCHMAKING_ERROR );
		return false;
	}

	// VVFIXME - Need to do probing, and pick best session, not just the first one
	if (!query.Results.Size())
	{
		UI_xboxErrorPopup( XB_POPUP_QUICKMATCH_NO_RESULTS );
		return false;
	}

	COptiMatchResult &server(query.Results[0]);

	XBL_MM_SetJoinType( VIA_QUICKMATCH );
	// VVFIXME - Experiment, leave this out so that the screen doesn't get trashed
	// right as we connect?
//	Menus_CloseAll();
	Net_XboxConnect(&server.SessionID, &server.KeyExchangeKey, &server.HostAddress);
/*
    // warn of lag and join(or not) via ui
    //
    if( cls.globalServers[bestSesh].ping < MINIMUM_QOS )
    {
        joinServerSlot = bestSesh;
	    Cvar_Set(CVAR_UI_XBOXREBOOTTITLE, " ");
        Cvar_Set(CVAR_UI_XBOXREBOOTMESSAGE, StringTable_Get(XSTR_GAMEPLAY_AFFECTED_BY_NETWORK));
		//Menus_ActivateByName("ingame_small_bgd");
        Menus_CloseByName("quickmatch_popup");
        Menus_ActivateByName("xblive_slow_warning");
       return false;
    }
    XBL_MM_JoinServer( bestSesh );
*/
	return true;
}
コード例 #8
0
/*!
    Returns true if sound facilities exist on the platform; otherwise
    returns false.

    If no sound is available, all QSound operations work silently and
    quickly. An application may choose either to notify the user if
    sound is crucial to the application or to operate silently without
    bothering the user.

    Note: On Windows this always returns true because some sound card
    drivers do not implement a way to find out whether it is available
    or not.
*/
bool QSound::isAvailable()
{
    return server().okay();
}
コード例 #9
0
ファイル: main.cpp プロジェクト: bytemaster/ltl
int main( int argc, char** argv ) {
  try {
  Wt::WServer server("ltl::server");
  server.setServerConfiguration( argc, argv, WTHTTP_CONFIGURATION );

  boost::filesystem::create_directories("db");
  ltl::server::ptr ms( new ltl::server( "db") );
  ltl::dbo::ptr<ltl::identity>   dan                 = ms->create_identity( "dan", "danprops" );
  ltl::dbo::ptr<ltl::identity>   scott               = ms->create_identity( "scott", "scottprops" );
  ltl::dbo::ptr<ltl::asset>      corn                = ms->create_asset( "corn", "gmo" );
  ltl::dbo::ptr<ltl::asset>      dollar              = ms->create_asset( "dollar", "$USD" );
  ltl::dbo::ptr<ltl::asset_note> dans_corn           = ms->create_asset_note(dan, corn, "dans corn", "cool" ); 
  ltl::dbo::ptr<ltl::asset_note> scott_dollar        = ms->create_asset_note(scott, dollar, "scott dollarn", "awesome" ); 

  ltl::dbo::ptr<ltl::account> dans_dans_corn_acnt       = ms->create_account( dan, dans_corn );
  ltl::dbo::ptr<ltl::account> scotts_dans_corn_acnt     = ms->create_account( scott, dans_corn );
  ltl::dbo::ptr<ltl::account> dans_scott_dollar_acnt    = ms->create_account( dan, scott_dollar );
  ltl::dbo::ptr<ltl::account> scotts_scott_dollar_acnt  = ms->create_account( scott, scott_dollar );

  try {
  // this should throw because scott has a 0 balance and cannot issue because he is not signer on note
  ltl::dbo::ptr<ltl::transaction> trx  = ms->transfer( "Sell corn", 10, scotts_dans_corn_acnt, dans_dans_corn_acnt );
  } catch ( const boost::exception& e ) {
    wlog("Expected Exception: %1%",boost::diagnostic_information(e));
  }

  slog( "creating first transaction" );
  // transfer 10 corn from dan_dans_corn to scotts_dans_corn
  ltl::dbo::ptr<ltl::transaction> trx  = ms->transfer( "Issue corn",10, dans_dans_corn_acnt, scotts_dans_corn_acnt );

  std::vector<ltl::sha1> req = trx->get_required_signatures();
  for( uint32_t i = 0; i < req.size(); ++i ) {
    slog( "required signature %1%", std::string(req[i]) );
  }

  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );
  slog( "Scott's Corn:\n%1%", scotts_dans_corn_acnt->to_string() );

  wlog( "Allocating Signature Numbers" );
  ms->allocate_signature_numbers( dans_dans_corn_acnt, 10 );
  ms->allocate_signature_numbers( scotts_dans_corn_acnt, 5 );
  ms->allocate_signature_numbers( dans_scott_dollar_acnt, 3 );
  ms->allocate_signature_numbers( scotts_scott_dollar_acnt, 3 );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );

  wlog( "Accepting Balance" );
  ms->accept_applied_transactions( dans_dans_corn_acnt );
  ms->accept_applied_transactions( scotts_dans_corn_acnt );
  ms->accept_applied_transactions( dans_scott_dollar_acnt );
  ms->accept_applied_transactions( scotts_scott_dollar_acnt );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );

  wlog( "Signing tranaction" );
  ms->sign_transaction( trx, dans_dans_corn_acnt );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );
  ms->sign_transaction( trx, scotts_dans_corn_acnt );
  slog( "Scott's Corn:\n%1%", scotts_dans_corn_acnt->to_string() );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );

  wlog( "Accepting Dan's Balance" );
  ms->accept_applied_transactions( dans_dans_corn_acnt );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );

  wlog( "Accepting Scott's Balance" );
  ms->accept_applied_transactions( scotts_dans_corn_acnt );
  slog( "Scott's Corn:\n%1%", scotts_dans_corn_acnt->to_string() );



  wlog( "Starting Market Order" );
  ltl::dbo::ptr<ltl::market_order> mo = ms->submit_order( ltl::market_order::buy, scotts_dans_corn_acnt, scotts_scott_dollar_acnt,
                    1000,  313, 1, ltl::to_ptime( boost::chrono::system_clock::now() ), ltl::to_ptime( boost::chrono::system_clock::now() + boost::chrono::minutes(60*24*30) ) );
  slog( "Scott's Corn:\n%1%", scotts_dans_corn_acnt->to_string() );
  slog( "Scott's Dollars:\n%1%", scotts_scott_dollar_acnt->to_string() );
  slog( "Dan's Corn:\n%1%", dans_dans_corn_acnt->to_string() );
  slog( "Dan's Dollars:\n%1%", dans_scott_dollar_acnt->to_string() );
 // trx->sign( dans_dans_corn_acnt );
  

  // at this point both dan & scott should have a pending, unsigned transaction in their inbox

  if( server.start() ) {
    int sig = Wt::WServer::waitForShutdown();
    std::cerr << "Shutting down (signal = " << sig <<")\n";
    server.stop();
  }

  } catch ( const boost::exception& e ) {
    std::cerr<<boost::diagnostic_information(e);
  } catch ( const std::exception& e ) {
    std::cerr<<boost::diagnostic_information(e);
  } catch ( ... ) {
    std::cerr<<"Unhandled exception\n";
  }
}
コード例 #10
0
/*!
    \overload

    Starts playing the sound specified by this QSound object.

    The function returns immediately.  Depending on the platform audio
    facilities, other sounds may stop or be mixed with the new
    sound. The sound can be played again at any time, possibly mixing
    or replacing previous plays of the sound.

    \sa fileName()
*/
void QSound::play()
{
    Q_D(QSound);
    d->looprem = d->looptotal;
    server().play(this);
}
コード例 #11
0
/*!
    Stops the sound playing.

    Note that on Windows the current loop will finish if a sound is
    played in a loop.

    \sa play()
*/
void QSound::stop()
{
    Q_D(QSound);
    server().stop(this);
    d->looprem = 0;
}
コード例 #12
0
/*!
    \obsolete

    Constructs a QSound object from the file specified by the given \a
    filename and with the given \a parent and \a name. Use the
    QSound() construcor and QObject::setObjectName() instead.

    \oldcode
        QSound *mySound = new QSound(filename, parent, name);
    \newcode
        QSounc *mySound = new QSound(filename, parent);
        mySound->setObjectName(name);
    \endcode
*/
QSound::QSound(const QString& filename, QObject* parent, const char* name)
    : QObject(*new QSoundPrivate(filename), parent)
{
    setObjectName(QString::fromAscii(name));
    server().init(this);
}
コード例 #13
0
/*!
    Constructs a QSound object from the file specified by the given \a
    filename and with the given \a parent.

    This may use more memory than the static play() function, but it
    may also play more immediately (depending on the underlying
    platform audio facilities).

    \sa play()
*/
QSound::QSound(const QString& filename, QObject* parent)
    : QObject(*new QSoundPrivate(filename), parent)
{
    server().init(this);
}
コード例 #14
0
/*!
    Plays the sound stored in the file specified by the given \a filename.

    \sa stop(), loopsRemaining(), isFinished()
*/
void QSound::play(const QString& filename)
{
    server().play(filename);
}
コード例 #15
0
ファイル: smtpauth.cpp プロジェクト: aox/aox
void SmtpAuth::execute()
{
    if ( !d->m ) {
        if ( server()->dialect() == SMTP::Lmtp ) {
            respond( 503, "Will not authenticate for LMTP", "5.5.0" );
            finish();
            return;
        }

        if ( server()->user() ) {
            respond( 503, "Already authenticated", "5.0.0" );
            finish();
            return;
        }

        if ( !server()->accessPermitted() ) {
            respond( 504, "TLS required for message submission", "5.7.0" );
            finish();
            return;
        }

        d->m = SaslMechanism::create( d->mech, this, server() );
        if ( !d->m ) {
            respond( 504, "Mechanism " + d->mech.quoted() + " not available",
                     "5.5.4" );
            finish();
            return;
        }

        server()->setInputState( SMTP::Sasl );
        d->m->readInitialResponse( d->r );
    }

    if ( d->m )
        d->m->readResponse( server()->readBuffer()->removeLine() );

    if ( !d->m->done() )
        return;

    if ( d->m->state() == SaslMechanism::Succeeded ) {
        if ( d->m->user()->login() == "anonymous" ) {
            respond( 235, "You may not submit mail", "2.0.0"  );
        }
        else {
            server()->authenticated( d->m->user() );
            respond( 235, "OK", "2.0.0" );
        }
    }
    else if ( d->m->state() == SaslMechanism::Terminated ) {
        respond( 501, "Authentication terminated", "5.0.0" );
    }
    else {
        respond( 535, "Authentication failed", "5.0.0" );
        if ( d->m->user() &&
             !d->m->user()->login().isEmpty() )
            log( "Authentication failed for " +
                 d->m->user()->login().ascii() );
        // huh. maybe we do want to use utf-8 in the logfile.
    }

    server()->setInputState( SMTP::Command );
    finish();
}
コード例 #16
0
ファイル: main.cpp プロジェクト: LightBitsLabs/osmosis
int main( int argc, char * argv [] )
{
	boost::program_options::options_description optionsDescription( "options" );
	optionsDescription.add_options()
		("help", "produce help message")
		("objectStoreRootPath", boost::program_options::value< std::string >()->default_value( "/var/lib/osmosis/objectstore" ),
			"Path where osmosis will store objects. relevant for 'server', 'purge', 'labellog' and 'leastrecentlyused' commands" )
		("serverTCPPort", boost::program_options::value< unsigned short >()->default_value( 1010 ),
			"the TCP port to bind to, if command is 'server'")
		( "objectStores", boost::program_options::value< std::string >()->default_value( "127.0.0.1:1010" ),
			"the object store to act againt. May be a '+' seperated list for 'checkout' command" )
		( "MD5", "use MD5, not SHA1 for hash in 'checkin' operation" )
		( "putIfMissing", "when command is 'checkout' or 'transfer', this flag will cause any objects received not from the "
		        "nearest object store to be put into all objects stores up to the one it was fetched from" )
		( "removeUnknownFiles", "for checkout: remove files from disk that are not in the dirlist being checked out" )
		( "myUIDandGIDcheckout", "for checkout: use my uid and gid" )
		( "ignore", boost::program_options::value< std::string >(),
			"for checkout: ignore the existance of all files in this ':' seperated list. "
			"if a directory was specified, ignored everything under it as well. specified paths "
			"must reside inside the checkout path" )
		( "transferDestination", boost::program_options::value< std::string >(),
			"destination object store to transfer the label into" )
		( "reportFile", boost::program_options::value< std::string >()->default_value( "" ),
			"periodically write report in JSON format into this file" )
		( "reportIntervalSeconds", boost::program_options::value< unsigned >()->default_value( 15 ),
			"period to report progress" )
		( "noChainTouch", "avoid touching fetched label in all object stores in chain (used for label bookeeping)" )
		( "keep", boost::program_options::value< std::string >()->default_value( "keepforever|bootstrap" ),
		  	"regular expression for labels to never erase. Only relevant under 'leastrecentlyused' command" )
		( "maximumDiskUsage", boost::program_options::value< std::string >(),
		  	"<number>M or <number>G for the amount of storage used for label objects before 'leastrecentlyused' starts erasing labels");

	boost::program_options::options_description positionalDescription( "positionals" );
	positionalDescription.add_options()
		( "command", boost::program_options::value< std::string >() )
		( "arg1", boost::program_options::value< std::string >() )
		( "arg2", boost::program_options::value< std::string >() );

	boost::program_options::positional_options_description positionalMapping;
	positionalMapping.add( "command", 1 ).add( "arg1", 1 ).add( "arg2", 1 );

	boost::program_options::options_description allOptions;
	allOptions.add( optionsDescription ).add( positionalDescription );

	boost::program_options::variables_map options;
	try {
		boost::program_options::store(
			boost::program_options::command_line_parser( argc, argv ).
				positional( positionalMapping ).options( allOptions ).
				run(),
			options );
		boost::program_options::notify( options );
	} catch ( boost::exception & e ) {
		TRACE_BOOST_EXCEPTION( e, "Unable to parse command line" );
		usage( optionsDescription );
		return 1;
	}

	if ( options.count( "help" ) ) {
		usage( optionsDescription );
		return 1;
	}

	try {
		std::string command = options[ "command" ].as< std::string >();
		if ( command == "server" ) {
			if ( options.count( "arg1" ) > 0 or options.count( "arg2" ) > 0 ) {
				TRACE_ERROR( "'workDir' or 'label' must not be present in command line"
						"if 'server' is specified as the command" );
				usage( optionsDescription );
				return 1;
			}
			server( options );
		} else if ( command == "checkin" )
			checkIn( options );
		else if ( command == "checkout" )
			checkOut( options );
		else if ( command == "transfer" )
			transfer( options );
		else if ( command == "listlabels" )
			listLabels( options );
		else if ( command == "eraselabel" )
			eraseLabel( options );
		else if ( command == "purge" )
			purge( options );
		else if ( command == "renamelabel" )
			renameLabel( options );
		else if ( command == "labellog" )
			dumpLabelLog( options );
		else if ( command == "leastrecentlyused" )
			leastRecentlyUsed( options );
		else if ( command == "testhash" )
			testHash( options );
		else {
			TRACE_ERROR( "Unknown command '" << command << "'" );
			usage( optionsDescription );
			return 1;
		}
	} catch ( boost::exception & e ) {
		TRACE_BOOST_EXCEPTION( e, "Terminated on a boost exception" );
		return 1;
	} catch ( Error & e ) {
		TRACE_ERROR( "Terminated on 'Error' exception: '" << e.what() << "' from " << e.backtrace() );
		return 1;
	} catch ( std::exception & e ) {
		TRACE_ERROR( "Terminated on std::exception: '" << e.what() );
		return 1;
	} catch ( ... ) {
		TRACE_ERROR( "Terminated on unknown exception" );
		return 1;
	}

	return 0;
}
コード例 #17
0
ファイル: bigfile-copy-mpi.c プロジェクト: sbird/bigfile
int main(int argc, char * argv[]) {

    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask);
    MPI_Comm_size(MPI_COMM_WORLD, &NTask);

    MPI_Type_contiguous(2, MPI_LONG, &MPI_TYPE_WORK);
    MPI_Type_commit(&MPI_TYPE_WORK);

    int ch;
    while(-1 != (ch = getopt(argc, argv, "n:N:vb:f:"))) {
        switch(ch) {
            case 'N':
            case 'n':
                Nfile = atoi(optarg);
                break;
            case 'b':
                sscanf(optarg, "%td", &buffersize);
                break;
            case 'f':
                newfilepath = optarg;
                break;
            case 'v':
                verbose = 1;
                break;
            default:
                usage();
        }
    }
    if(argc - optind + 1 != 4) {
        usage();
    }
    argv += optind - 1;
    if(0 != big_file_mpi_open(&bf, argv[1], MPI_COMM_WORLD)) {
        fprintf(stderr, "failed to open: %s\n", big_file_get_error_message());
        exit(1);
    }
    if(0 != big_file_mpi_open_block(&bf, &bb, argv[2], MPI_COMM_WORLD)) {
        fprintf(stderr, "failed to open: %s\n", big_file_get_error_message());
        exit(1);
    }
    if(Nfile == -1 || bb.Nfile == 0) {
        Nfile = bb.Nfile;
    }
    if(newfilepath == NULL) {
        newfilepath = argv[1];
    }
    if(0 != big_file_mpi_create(&bfnew, newfilepath, MPI_COMM_WORLD)) {
        fprintf(stderr, "failed to open: %s\n", big_file_get_error_message());
        exit(1);
    }
    if(0 != big_file_mpi_create_block(&bfnew, &bbnew, argv[3], bb.dtype, bb.nmemb, Nfile, bb.size, MPI_COMM_WORLD)) {
        fprintf(stderr, "failed to create temp: %s\n", big_file_get_error_message());
        exit(1);
    }

    if(bbnew.size != bb.size) {
        abort();
    }

    /* copy attrs */
    size_t nattr;
    BigAttr * attrs = big_block_list_attrs(&bb, &nattr);
    int i;
    for(i = 0; i < nattr; i ++) {
        BigAttr * attr = &attrs[i];
        big_block_set_attr(&bbnew, attr->name, attr->data, attr->dtype, attr->nmemb);
    }

    if(bb.nmemb > 0 && bb.size > 0) {
    /* copy data */
        if(ThisTask == 0) {
            server();
        } else {
            slave();
        }
    }
    if(0 != big_block_mpi_close(&bbnew, MPI_COMM_WORLD)) {
        fprintf(stderr, "failed to close new: %s\n", big_file_get_error_message());
        exit(1);
    }
    big_block_mpi_close(&bb, MPI_COMM_WORLD);
    big_file_mpi_close(&bf, MPI_COMM_WORLD);
    big_file_mpi_close(&bfnew, MPI_COMM_WORLD);
    return 0;
}
コード例 #18
0
ファイル: main.c プロジェクト: mihaicarabas/dragonfly
int
main(int argc, char **argv)
{
	char *arg;
	int cmdargs;
	char *dhosts[NHOSTS], **hp = dhosts;

	cmdargs = 0;

	pw = getpwuid(userid = getuid());
	if (pw == NULL) {
		fprintf(stderr, "%s: Who are you?\n", argv[0]);
		exit(1);
	}
	strcpy(user, pw->pw_name);
	strcpy(homedir, pw->pw_dir);
	groupid = pw->pw_gid;
	gethostname(host, sizeof(host));
	strcpy(tempfile, _PATH_TMP);
	strcat(tempfile, _RDIST_TMP);
	if ((tempname = rindex(tempfile, '/')) != NULL)
		tempname++;
	else
		tempname = tempfile;

	while (--argc > 0) {
		if ((arg = *++argv)[0] != '-')
			break;
		if (!strcmp(arg, "-Server"))
			iamremote++;
		else while (*++arg)
			switch (*arg) {
			case 'P':
				if (--argc <= 0)
					usage();
				path_rsh = *++argv;
				break;

			case 'f':
				if (--argc <= 0)
					usage();
				distfile = *++argv;
				if (distfile[0] == '-' && distfile[1] == '\0')
					fin = stdin;
				break;

			case 'm':
				if (--argc <= 0)
					usage();
				if (hp >= &dhosts[NHOSTS-2]) {
					fprintf(stderr, "rdist: too many destination hosts\n");
					exit(1);
				}
				*hp++ = *++argv;
				break;

			case 'd':
				if (--argc <= 0)
					usage();
				define(*++argv);
				break;

			case 'D':
				debug++;
				break;

			case 'c':
				cmdargs++;
				break;

			case 'n':
				if (options & VERIFY) {
					printf("rdist: -n overrides -v\n");
					options &= ~VERIFY;
				}
				nflag++;
				break;

			case 'q':
				qflag++;
				break;

			case 'b':
				options |= COMPARE;
				break;

			case 'R':
				options |= REMOVE;
				break;

			case 'v':
				if (nflag) {
					printf("rdist: -n overrides -v\n");
					break;
				}
				options |= VERIFY;
				break;

			case 'w':
				options |= WHOLE;
				break;

			case 'y':
				options |= YOUNGER;
				break;

			case 'h':
				options |= FOLLOW;
				break;

			case 'i':
				options |= IGNLNKS;
				break;

			default:
				usage();
			}
	}
	*hp = NULL;

	seteuid(userid);
	mktemp(tempfile);

	if (iamremote) {
		server();
		exit(nerrs != 0);
	}

	if (cmdargs)
		docmdargs(argc, argv);
	else {
		if (fin == NULL) {
			if(distfile == NULL) {
				if((fin = fopen("distfile","r")) == NULL)
					fin = fopen("Distfile", "r");
			} else
				fin = fopen(distfile, "r");
			if(fin == NULL) {
				perror(distfile ? distfile : "distfile");
				exit(1);
			}
		}
		yyparse();
		if (nerrs == 0)
			docmds(dhosts, argc, argv);
	}

	exit(nerrs != 0);
}
コード例 #19
0
/*===========================================================================

FUNCTION     : main
DEPENDENCIES : None

RETURN VALUE : None

============================================================================*/
int main(int argc, char *argv[])
{
        int pid, cid, status;
        struct sockaddr_rc ra;
        int length, retval = -1;
        char addr[BTADDR_SIZE];
        struct sigaction actions;
        memset(&actions, 0, sizeof(actions));
        sigemptyset(&actions.sa_mask);
        actions.sa_flags = 0;
        actions.sa_handler = abort_handler;

        if (argc != 2) {
                LOGE("Invalid arguements: Usage:  sapd <rfcomm_channel_no>");
                return -1;
        }

        /*Ignore the signals from child to
        prevent becoming zombie*/
        signal(SIGCHLD, SIG_IGN);
        /*Ignore the SIGPIPE signal, this signal will
          emited incase there is an error writing to
          SAP BT App socket */
        signal(SIGPIPE, SIG_IGN);
        if (sigaction(SIGTERM,&actions,NULL) < 0) {
                LOGE("Error in sigaction in %s:  %s\n", __func__, strerror(errno));
                return -1;
        }
        /*Create the pipe between parent and child
        with which all the server side events like
        disconnect,card status event can be communicated
        to child session*/
        if (pipe (server_evt_pipe))
        {
                LOGE ("Pipe Creation failed :%s\n", strerror(errno));
                return -1;
        }

        LOGV("Event pipe created\n");

        while (1) {
                length = sizeof(struct sockaddr_un);
                local_sk = create_server_socket (SAP_SERVER);
                if (local_sk == -1)
                {
                    LOGE("Fatal Error : Could not create Socket for BT SAP:\n");
                    break;
                }

                /*This is the parent daemon, which would keep listening
                for the incoming connections from SAP BT App layer */
                /*Once accepted, It forks a child which takes care of SAP request
                processing, Once the SAP disconnects, parent can accept
                further connections
                */
                conn_sk = accept(local_sk, (struct sockaddr *)&ra, &length);

                LOGV("Accepted incoming connection from SAP BT App");
                if (conn_sk < 0) {
                        close(local_sk);
                        if (errno == EBADF) {
                                LOGE("Invalid local Socket descriptor: %d err: %s\n", local_sk, strerror(errno));
                                /*This signifys that exe is aborted and should be exited*/
                                break;
                        } else {
                                /*remote socket failure case
                                skip the further part, so that SAP server
                                will be back in its wait loop*/
                                LOGE("Invalid local Socket descriptor: %d err: %s\n", local_sk, strerror(errno));
                                continue;
                        }
                }

                /*Process the request in a new child*/
                switch (cid = fork()){
                        case 0:
                                /*In child*/
                                LOGV("In Child process\n");
                                pid = getpid();
                                /*child doesn't need local socket any more*/
                                close(local_sk);
                                /*get SIGHUP on parent's death*/
                                prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
                                /*server will handle the necessary
                                 */
                                LOGV("Starting the server in Child\n");
                                retval = server(conn_sk, server_evt_pipe[0]);
                                /*Exit from child*/
                                LOGV("Exiting from the child\n");
                                exit(0);
                                break;
                        case -1:
                                LOGE("%s: Can't fork: %s\n", __func__, strerror(errno));
                        default:
                                /*Don't need to have ref to
                                remote socket in parent*/
                                LOGV("Closing the remote socket in Parent\n");
                                close(conn_sk);
                                /*Don't need to accept futher connections?*/
                                close(local_sk);

                                LOGV("Waiting for the child to finish....\n");
                                waitpid(cid, &status, 0);
                                LOGV("Parent: Status of the child %d is %d\n", cid, status);
                                break;
                                /*Parent will go back to his main listening loop
                                for further incoming connections*/
                }
        }
        return 0;
}
コード例 #20
0
ファイル: dist_async_sum.cpp プロジェクト: AI42/mshadow
int CreateServerNode(int argc, char *argv[]) {
  mshadow::ps::MShadowServerNode<float> server(argc, argv);
  return 0;
}
コード例 #21
0
int main (int argc, char * argv[])
{
  Miro::Log::init(argc, argv);
  Miro::Server server(argc, argv);

  // server part
  try {
    std::string name = "AMI";
    XMP::AmiImpl * ami = new XMP::AmiImpl();

    server.activateNamedObject(name, ami);
    server.detach(5);
  }
  catch (CORBA::Exception const& e) {
    MIRO_LOG_OSTR(LL_CRITICAL, "CORBA exception:\n" << e);
  }

  // client part
  try {
    // anything that has a callback is actually a server...
    Miro::Server server(argc, argv);
    XMP::Ami_var ami = server.resolveName<XMP::Ami>("AMI");

    // we just run the ORB in a background thread
    server.detach(3);

    //--------------------------------------------------------------------------
    // calling a method without a return arguement
    {
      //------------------------------------------------------------------------
      // synchronous method call

      std::cout << "synchronous call to s0." << std::endl;
      ami->s0(5);
      std::cout << "s0 returned." << std::endl;
      
      //------------------------------------------------------------------------
      // asynchronous upcall, not caring about the return value
      std::cout << "asynchronous (oneway) call to s." << std::endl;
      ami->sendc_s(NULL);
      std::cout << "s returned." << std::endl;

      //------------------------------------------------------------------------
      // asynchronous call with reply handler

      // the generic AMI helper class
      // instanciated with our generic callback implemenation
      Miro::AmiHelper<XMP::AMI_Ami_s> h;
    
      std::cout << "asynchronous call to s." << std::endl;
      ami->sendc_s(h.handler());
      std::cout << "s returned." << std::endl;
      
      std::cout << "wait for s to finish." << std::endl;
      h.wait();
      // checking return value, in case there was an exception:
      h.rc();
      std::cout << "s finished." << std::endl;


      //------------------------------------------------------------------------
      // asynchronous upcall, not caring about the return value
#ifdef ASDF
      std::cout << "asynchronous (oneway) call to s0." << std::endl;
      ami->sendc_s0(NULL, 4);
      std::cout << "s0 returned." << std::endl;

      //------------------------------------------------------------------------
      // asynchronous call with reply handler

      // the generic AMI helper class
      // instanciated with our generic callback implemenation
      Miro::AmiHelper<XMP::AMI_Ami_s0> h0;
    
      std::cout << "asynchronous call to s0." << std::endl;
      ami->sendc_s0(h0.handler(), 4);
      std::cout << "s0 returned." << std::endl;
      
      std::cout << "wait for s0 to finish." << std::endl;
      h0.wait();
      // checking return value, in case there was an exception:
      h0.rc();
      std::cout << "s0 finished." << std::endl;
#endif
    }
    //--------------------------------------------------------------------------
    // calling a method with one single return arguement
    {
      //------------------------------------------------------------------------
      // synchronous method call

      std::cout << "synchronous call to s1." << std::endl;
      int rc = ami->s1();
      std::cout << "s1 returned:" << rc << std::endl;

      //------------------------------------------------------------------------
      // asynchronous call with reply handler

      // the generic AMI helper class
      Miro::AmiHelper<XMP::AMI_Ami_s1> h1;

      std::cout << "asynchronous call to s1." << std::endl;
      ami->sendc_s1(h1.handler());
      std::cout << "s1 returned." << std::endl;

      std::cout << "wait for s1 finish!" << std::endl;
      h1.wait();
      std::cout << "s1 finished - rc:" << h1.rc() << std::endl;
    
      //------------------------------------------------------------------------
      // asynchronous call with dangling reply handler
   
      Miro::AmiHelper<XMP::AMI_Ami_s1> h1b;
      std::cout << "asynchronous call to s1." << std::endl;
      ami->sendc_s1(h1b.handler());
      std::cout << "s1 returned." << std::endl;
      std::cout << "ooops we forgot towait for completion." << std::endl;
      std::cout << "how nice, that this results no memory leak." << std::endl;
    }

    //--------------------------------------------------------------------------
    // calling a method which throws an exception
    try {
      Miro::AmiHelper<XMP::AMI_Ami_s2> h2;

      std::cout << "asynchronous call to s2." << std::endl;
      ami->sendc_s2(h2.handler());
      std::cout << "s2 returned." << std::endl;
      
      std::cout << "wait for s2 finish!" << std::endl;
      h2.wait();
      std::cout << "s2 finished." << std::endl;
      
      h2.rc();
    }
    catch (XMP::EAmi const& e) {
      std::cout << "EAmi exception: " << e.what << std::endl;
    }

    std::cout << "shuting down server." << std::endl;
    server.shutdown();
    server.wait();
    std::cout << "server down." << std::endl;
  }
  catch (CORBA::Exception const& e) {
    MIRO_LOG_OSTR(LL_CRITICAL, "CORBA exception:\n" << e);
    server.shutdown();
    std::cout << "what's next?" << std::endl;
  }
  std::cout << "cleanup" << std::endl;
  return 0;
}
コード例 #22
0
ファイル: ncTh.c プロジェクト: bollain/netClone
int main(int argc, char **argv) {

	//First we read our arguments from the command line
	while ((c = getopt (argc, argv, "kl:vrw:p:")) != -1)
		switch(c)
		{
			case 'l':
				listenPort = optarg;
				lflag = 1;
				break;
			case 'k':
				kflag = 1;
				break;
			case 'v':
				vflag = 1;
				break;
			case 'w':
				wflag = 1;
				timeOut = atoi(optarg);
				break;
			case 'r':
				rflag = 1;
				break;
			case 'p':
				pflag = 1;
				sourcePort = atoi(optarg);
				break;
			default:
				usage(argv[0]);
				exit(1);
		}

	  //Get hostname and destination port only if -l is not on
	  if (lflag != 1){
		  argn = optind;
		  hostName = argv[argn];
		  //Make sure a port was provided in argv, or we will get a seg fault
		  if(argn+1 >= argc){
		  	usage(argv[0]);
		  	exit(1);
		  } else {
		  	destPort = argv[argn+1];
		  }
		}

	//It is an error to use the -k option without the -l option.
	if(kflag == 1 && lflag == 0){
		usage(argv[0]);
		exit(1);
	}
	
	//It is an error to use the -p option in conjunction with the -l option.
	if (lflag == 1 && pflag ==1){
		usage(argv[0]);
		exit(1);
	}

	//The r option can only be used with the -l option
	if (rflag == 1 && lflag == 0){
		usage(argv[0]);
		exit(1);
	}

	//The w cannot be used with the l option
	if (wflag == 1 && lflag == 1){
		usage(argv[0]);
		exit(1);
	}

    //For debugging
    if(vflag){
	    printf ("kflag = %d, lflag = %d, vflag = %d, wflag= %d, rflag= %d, pflag =%d\n",
		kflag, lflag, vflag, wflag, rflag, pflag);
		printf("The time out is : %d\n", timeOut);
		printf("The sourcePort num is : %d\n", sourcePort);
		printf("The listenPort num is : %s\n", listenPort);
		printf("The hostName num is : %s\n", hostName);
		printf("The destPort num is : %s\n", destPort);
	}

	//Call server() function for -l flag
	if(lflag){
		server(listenPort, kflag);
	}

	//For client
	if(lflag == 0){
		client(hostName, destPort);
	}

    return 0;

}
コード例 #23
0
ファイル: main.c プロジェクト: SanthoshGunturu/finalproject
int main(int argc, const char * argv[]) {
    
    char *keystoredir;
    char *arg_interface = NULL;
    char *token, *dup;
    
    int i;
    int num_input_interfaces = 0;
    
    uint16_t src;
    
    struct stat s;
    struct interface *input_interface;
    
    if (argc <= 5) {
        print_usage();
        exit(1);
    }
    
    if (!((strcmp("-s", argv[1]) == 0) || (strcmp("-c", argv[1]) == 0))) {
        print_usage();
        exit(1);
    }
    
    if (strcmp("-src", argv[2]) != 0) {
        print_usage();
        exit(1);
    }
    
    if (strcmp("-d", argv[4]) != 0) {
        print_usage();
        exit(1);
    }
    
    if (strcmp("-i", argv[6]) != 0) {
        print_usage();
        exit(1);
    }
    
    src = (uint16_t) atoi(argv[3]);
    keystoredir = strdup(argv[5]);
    
    
    // Remove / if the dirname ends with a slash
    if (keystoredir[strlen(keystoredir)-1] == '/') {
        keystoredir[strlen(keystoredir)-1] = '\0';
    }
    
    // Check if the keystore directory exists
    if (stat(keystoredir, &s) == -1) {
        fprintf(stderr, "Error: keystore %s does not exist\n", keystoredir);
        exit(1);
    }
    else {
        if(!S_ISDIR(s.st_mode)) {
            fprintf(stderr, "Error: keystore %s is not a directory\n", keystoredir);
            exit(1);
        }
    }
    
    arg_interface = strdup(argv[7]);
    
    /*
     * Network Interfaces
     *
     */
    // Count commas to get the upper bound of the number of interfaces
    for (i=0; i<strlen(arg_interface); i++) {
        if (arg_interface[i] == ',') num_input_interfaces++;
    }
    num_input_interfaces++;
    
    // Allocate input interface array
    input_interface = (struct interface *) malloc(num_input_interfaces * sizeof(struct interface));
    
    // Parse input interfaces
    num_input_interfaces = 0;
    dup = strdup(arg_interface);
    while ((token = strtok(dup, ",")) != NULL) {
        
        strcpy(input_interface[num_input_interfaces].interface_name, token);
        fill_interface_info(&input_interface[num_input_interfaces]);
        
        // Interface name is valid
        if (input_interface[num_input_interfaces].interface_index != -1) {
            num_input_interfaces++;
        }
        
        dup = NULL;
        
    }
    free(arg_interface);
    free(token);
    
    // Check if the number of interfaces is at least 1
    if (num_input_interfaces <= 0) {
        fprintf(stderr, "Error: no valid network interfaces\n");
        exit(1);
    }
    
    // Print listening interfaces information
    #ifdef _VERBOSE
    fprintf(stderr, "[NETWORK INTERFACES]\n");
    fprintf(stderr, "   Number of network interfaces: %d\n", num_input_interfaces);
    fprintf(stderr, "   %-5s %-6s %-19s %-15s\n", "Dev", "DevId", "Interface MAC addr", "Inf IP addr");
    for(i=0; i<num_input_interfaces; i++) {
        fprintf(stderr, "%2d ", i+1);
        fprintf_interface(stderr, &input_interface[i]);
    }
    fprintf(stderr, "\n");
    #endif
    
    
    
    if (strcmp("-s", argv[1]) == 0) {
        server(src, keystoredir, num_input_interfaces, &input_interface);
    }
    else if (strcmp("-c", argv[1]) == 0) {
        client(src, keystoredir, num_input_interfaces, &input_interface);
    }
    
    return 0;
    
}
コード例 #24
0
ファイル: Test_IpRestriction.cpp プロジェクト: uvbs/klib
int test_main(int argc, char **argv)
{
    //util::CommandLineOption<int> port("port", util::Ports::getNext(), "port number");
    util::CommandLine::getSingleton().parse(argc, argv);

    int port = 0;

    std::vector<std::string> ips;
    ips.push_back("www.usatoday.com");
    ips.push_back("www.sunet.se");
    ips.push_back("www.google.com");

    X x;
    {
        port = util::Ports::getNext();
        RCF::RcfServer server(port);
        server.setAllowedClientIps(ips);
        server.bind<I_X>(x);
        server.start();

        try 
        {
            RcfClient<I_X> client("localhost", port);
            client.f();
            BOOST_CHECK(1==0);
        }
        catch(const RCF::Exception &e)
        {
            RCF_TRACE("")(e);
            BOOST_CHECK(1==1);
        }

        ips = server.getAllowedClientIps();
        ips.push_back("localhost");
        server.setAllowedClientIps(ips);

        RcfClient<I_X> client("localhost", port);
        client.f();
    }

    // test interface restriction

    // loopback interface
    std::vector<std::string> interfaces;
    interfaces.push_back("127.0.0.1");
    interfaces.push_back("localhost");
    
    for (unsigned int i=0; i<interfaces.size(); i++)
    {
        port = util::Ports::getNext();
        RCF::RcfServer server(port);
        server.bind<I_X>(x);
        server.setNetworkInterface(interfaces[i]);
        server.start();

        RcfClient<I_X>("localhost", port).f();
        BOOST_CHECK(1==1);
    }
    
    // erroneous interface
    {
        port = util::Ports::getNext();
        RCF::RcfServer server(port);
        server.bind<I_X>(x);
        server.setNetworkInterface("1.2.3.4");
        try 
        {
            server.start();
            BOOST_CHECK(1==0);
        }
        catch (const RCF::Exception &e)
        {
            BOOST_CHECK(1==1);
            RCF_TRACE("")(e);
        }
    }

    return boost::exit_success;
}
コード例 #25
0
void ComTdbHbaseAccess::displayContents(Space * space,ULng32 flag)
{
  ComTdb::displayContents(space,flag & 0xFFFFFFFE);

  if(flag & 0x00000008)
    {
      char buf[1000];

      str_sprintf(buf, "\nFor ComTdbHbaseAccess :");
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "accessType_ = %s", (char*)getAccessTypeStr(accessType_));
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "accessDetail_ = %s", getNodeName());
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      if (samplingRate_ > 0)
        {
          // str_printf does not handle %f correctly, format as string first.
          char sbuf[20];
          snprintf(sbuf, sizeof(sbuf), "%f", samplingRate_);
          str_sprintf(buf, "samplingRate_ = %s", sbuf);
          space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
        }

      if (tableName_)
	{
	  str_sprintf(buf, "tableName_ = %s", (char*)tableName_);
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
	}

      str_sprintf(buf, "asciiTI_ = %d, convertTI_ = %d, rowIdTI_ = %d, returnedTI_ = %d",
		  asciiTuppIndex_, convertTuppIndex_, rowIdTuppIndex_, returnedTuppIndex_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "rowIdAsciiTI_ = %d, updateTI_ = %d, mergeInsertTI_ = %d",
		  rowIdAsciiTuppIndex_, updateTuppIndex_, mergeInsertTuppIndex_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "returnedFetchedTI_ = %d, returnedUpdatedTI_ = %d, mergeInsertRowIdTI_ = %d",
		  returnedFetchedTuppIndex_, returnedUpdatedTuppIndex_,
		  mergeInsertRowIdTuppIndex_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "hbaseTimestampTI_ = %d, hbaseVersionTI_ = %d",
                  hbaseTimestampTuppIndex_, hbaseVersionTuppIndex_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "asciiRowLen_ = %d, convertRowLen_ = %d, rowIdLen_ = %d, outputRowLen_ = %d", 
		  asciiRowLen_, convertRowLen_, rowIdLen_, outputRowLen_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "updateRowLen_ = %d, returnFetchedRowLen_ = %d, returnUpdateedRowLen_ = %d", 
		  updateRowLen_, returnFetchedRowLen_, returnUpdatedRowLen_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "mergeInsertRowLen_ = %d, keyLen_ = %d", 
		  mergeInsertRowLen_, keyLen_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "Flag = %b",flags_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      str_sprintf(buf, "server_ = %s, zkPort_ = %s", server(), zkPort());
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

      if ((getHbaseAccessOptions()) && (getHbaseAccessOptions()->multiVersions()))
        {
          str_sprintf(buf, "numVersions = %d", getHbaseAccessOptions()->getNumVersions());
          space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
        }

      if (listOfFetchedColNames())
	{
	  str_sprintf(buf, "\nlistOfFetchedColNames_(numEntries = %d):\n",
		      listOfFetchedColNames()->numEntries());
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	  if (sqHbaseTable())
	    showColNames(listOfFetchedColNames(), space);
	  else
	    showStrColNames(listOfFetchedColNames(), space);
	}

      if (listOfUpDeldColNames())
	{
	  str_sprintf(buf, "\nlistOfUpDeldColNames_(numEntries = %d):\n",
		      listOfUpDeldColNames()->numEntries());
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
	  
	  if (sqHbaseTable())
	    showColNames(listOfUpDeldColNames(), space);
	  else
	    showStrColNames(listOfUpDeldColNames(), space);

	  /*
	  if (updelColnameIsStr())
	    showStrColNames(listOfUpDeldColNames(), space);
	  else
	    showColNames(listOfUpDeldColNames(), space);
	  */
	}

      if (0)//listOfMergedColNames())
	{
	  str_sprintf(buf, "\nlistOfMergedColNames_(numEntries = %d):\n",
		      listOfMergedColNames()->numEntries());
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
	  
	  showColNames(listOfMergedColNames(), space);
	}

     if (listOfScanRows())
	{
	  str_sprintf(buf, "\nlistOfScanRows_(numEntries = %d):",
		      listOfScanRows()->numEntries());
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	  listOfScanRows()->position();
	  for (Lng32 i = 0; i < listOfScanRows()->numEntries(); i++)
	    {
	      HbaseScanRows * hsr = (HbaseScanRows*)listOfScanRows()->getNext();

	      str_sprintf(buf, "\n  Entry #%d:", i+1);
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	      str_sprintf(buf, "    beginRowId_%s = ",
			  (hsr->beginKeyExclusive_ ? "(excl)" : "(incl)")); 
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
	      
	      displayRowId(space, hsr->beginRowId());
	      
	      str_sprintf(buf, "    endRowId_%s = ",
			  (hsr->endKeyExclusive_ ? "(excl)" : "(incl)")); 			  
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	      displayRowId(space, hsr->endRowId());

	      if (0) //hsr->colNames())
		{
		  str_sprintf(buf, "\n    colNames_(numEntries = %d):",
			      hsr->colNames()->numEntries());
		  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		  
		  hsr->colNames()->position();
		  for (Lng32 j = 0; j < hsr->colNames()->numEntries(); j++)
		    {
		      str_sprintf(buf, "\n      Entry #%d:", j+1);
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		      
		      char * colName = (char*)hsr->colNames()->getNext();
		      str_sprintf(buf, "        colName='%s'", colName);
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		    } // for
		} // if colNames

	      str_sprintf(buf, "\n    colTS_=%Ld",
			  hsr->colTS_);
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	    } // for
	} // if

      if (listOfGetRows())
	{
	  str_sprintf(buf, "\nlistOfGetRows_(numEntries = %d):",
		      listOfGetRows()->numEntries());
	  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	  listOfGetRows()->position();
	  for (Lng32 i = 0; i < listOfGetRows()->numEntries(); i++)
	    {
	      HbaseGetRows * hgr = (HbaseGetRows*)listOfGetRows()->getNext();

	      str_sprintf(buf, "\n  Entry #%d:", i+1);
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	      if (hgr->rowIds())
		{
		  str_sprintf(buf, "\n    rowIds_(numEntries = %d):",
			      hgr->rowIds()->numEntries());
		  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		  
		  hgr->rowIds()->position();
		  for (Lng32 j = 0; j < hgr->rowIds()->numEntries(); j++)
		    {
		      str_sprintf(buf, "      Entry #%d:", j+1);
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		      
		      char * rowId = (char*)hgr->rowIds()->getNext();

		      ExpTupleDesc * asciiSourceTD =
			workCriDesc_->getTupleDescriptor(rowIdAsciiTuppIndex_);
		      
		      str_sprintf(buf, "      rowId_= ");
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

		      displayRowId(space, rowId);
		    } // for
		  
		} // if

	      if (0) //hgr->colNames())
		{
		  str_sprintf(buf, "\n    colNames_(numEntries = %d):",
			      hgr->colNames()->numEntries());
		  space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		  
		  hgr->colNames()->position();
		  for (Lng32 j = 0; j < hgr->colNames()->numEntries(); j++)
		    {
		      str_sprintf(buf, "      Entry #%d:", j+1);
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		      
		      char * colName = (char*)hgr->colNames()->getNext();
		      str_sprintf(buf, "        colName='%s'", colName);
		      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
		    } // for
		} // if

	      str_sprintf(buf, "\n    colTS_=%Ld",
			  hgr->colTS_);
	      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));

	    } // for
	} // if
      if (getHbaseSnapshotScanAttributes() &&
          getHbaseSnapshotScanAttributes()->getUseSnapshotScan())
      {
        str_sprintf(buf, "use_snapshot_scan = %s, snapshot_name = %s, snapshot_temp_location = %s",
                    "TRUE",
                    getHbaseSnapshotScanAttributes()->getSnapshotName(),
                    getHbaseSnapshotScanAttributes()->getSnapScanTmpLocation());
        space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(short));
      }
      
    }
  
  if(flag & 0x00000001)
    {
      displayExpression(space,flag);
      displayChildren(space,flag);
    }
}
コード例 #26
0
bool ErrorReport::SendReport(ErrorReport::IProgressNotifier* pProgressNotifier)
{
	int nbFilesToSend = 0;
	for(FileList::const_iterator it = m_AttachedFiles.begin(); it != m_AttachedFiles.end(); ++it) 
	{
		if(it->attachToReport)
			nbFilesToSend++;
	}

	pProgressNotifier->taskStarted("Sending crash report", 3 + nbFilesToSend);
	
	std::string userAgent = "Arx Libertatis Crash Reporter (" + arx_version + ")";
	TBG::Server server("https://bugs.arx-libertatis.org", userAgent);
	
	// Login to TBG server
	pProgressNotifier->taskStepStarted("Connecting to the bug tracker");
	bool bLoggedIn = server.login(m_Username, m_Password);
	pProgressNotifier->taskStepEnded();
	if(!bLoggedIn)
	{
		pProgressNotifier->setError("Could not connect to the bug tracker");
		pProgressNotifier->setDetailedError(server.getErrorString());
		return false;
	}
	
	// Look for existing issue
	int issue_id = -1;
	pProgressNotifier->taskStepStarted("Searching for existing issue");
	if(!m_ReportUniqueID.isEmpty()) {
		m_IssueLink = server.findIssue(m_ReportUniqueID, issue_id);
	}
	pProgressNotifier->taskStepEnded();
	
	// Create new issue if no match was found
	if(issue_id == -1) {
		
		pProgressNotifier->taskStepStarted("Creating new issue");
		m_IssueLink = server.createCrashReport(m_ReportTitle, m_ReportDescription,
		                                       m_ReproSteps, tbg_version_id, issue_id);
		if(m_IssueLink.isNull()) {
			pProgressNotifier->taskStepEnded();
			pProgressNotifier->setError("Could not create a new issue on the bug tracker");
			pProgressNotifier->setDetailedError(server.getErrorString());
			return false;
		}

		// Set OS
#if   ARX_PLATFORM == ARX_PLATFORM_WIN32
		int os_id = TBG::Server::OS_Windows;
#elif ARX_PLATFORM == ARX_PLATFORM_LINUX
		int os_id = TBG::Server::OS_Linux;
#elif ARX_PLATFORM == ARX_PLATFORM_MACOSX
		int os_id = TBG::Server::OS_MacOSX;
#elif ARX_PLATFORM == ARX_PLATFORM_BSD
		#if defined(__FreeBSD__)
		int os_id = TBG::Server::OS_FreeBSD;
		#else
		int os_id = TBG::Server::OS_BSD;
		#endif
#else
		int os_id = TBG::Server::OS_Other;
#endif
		server.setOperatingSystem(issue_id, os_id);

		// Set Architecture
		int arch_id;
		if(m_ProcessArchitecture == ARX_ARCH_X86_64)
			arch_id = TBG::Server::Arch_Amd64;
		else if(m_ProcessArchitecture == ARX_ARCH_X86)
			arch_id = TBG::Server::Arch_x86;
		else
			arch_id = TBG::Server::Arch_Other;
		server.setArchitecture(issue_id, arch_id);

		pProgressNotifier->taskStepEnded();
	}
	else
	{
		if(!m_ReproSteps.isEmpty())
		{
			pProgressNotifier->taskStepStarted("Duplicate issue found, adding information");
			bool bCommentAdded = server.addComment(issue_id, m_ReproSteps);
			pProgressNotifier->taskStepEnded();
			if(!bCommentAdded)
			{
				pProgressNotifier->setError("Failure occured when trying to add information to an existing issue");
				pProgressNotifier->setDetailedError(server.getErrorString());
				return false;
			}
		}
	}

	// Send files
	QString commonPath;
	for(FileList::const_iterator it = m_AttachedFiles.begin(); it != m_AttachedFiles.end(); ++it) 
	{
		// Ignore files that were removed by the user.
		if(!it->attachToReport)
			continue;

		// One more check to verify that the file still exists.
		if(!fs::exists(it->path))
			continue;

		pProgressNotifier->taskStepStarted(QString("Sending file \"%1\"").arg(it->path.filename().c_str()));
		QString path = it->path.parent().string().c_str();
		QString file = it->path.string().c_str();
		QString name = it->path.filename().c_str();
		if(server.attachFile(issue_id, file, name, m_SharedMemoryName)) {
			commonPath.clear();
		} else {
			m_failedFiles.append(file);
			if(it == m_AttachedFiles.begin()) {
				commonPath = path;
			} else if(path != commonPath) {
				commonPath.clear();
			}
		}
		pProgressNotifier->taskStepEnded();
	}
	if(!commonPath.isEmpty() && m_failedFiles.count() > 1) {
		m_failedFiles.clear();
		m_failedFiles.append(commonPath);
	}
	
	return true;
}
コード例 #27
0
TEST(CanAcceptanceFilter, Basic_test)
{
    uavcan::GlobalDataTypeRegistry::instance().reset();
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::camera_gimbal::AngularCommand> _reg1;
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::air_data::Sideslip> _reg2;
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::air_data::TrueAirspeed> _reg3;
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::air_data::AngleOfAttack> _reg4;
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::ahrs::AHRS> _reg5;
    uavcan::DefaultDataTypeRegistrator<uavcan::equipment::air_data::StaticPressure> _reg6;
    uavcan::DefaultDataTypeRegistrator<uavcan::protocol::file::BeginFirmwareUpdate> _reg7;

    SystemClockDriver clock_driver;
    CanDriverMock can_driver(1, clock_driver);
    TestNode node(can_driver, clock_driver, 24);

    uavcan::Subscriber<uavcan::equipment::camera_gimbal::AngularCommand,
                    SubscriptionListener<uavcan::equipment::camera_gimbal::AngularCommand>::ExtendedBinder> sub_1(node);
    uavcan::Subscriber<uavcan::equipment::air_data::Sideslip,
                       SubscriptionListener<uavcan::equipment::air_data::Sideslip>::ExtendedBinder> sub_2(node);
    uavcan::Subscriber<uavcan::equipment::air_data::TrueAirspeed,
                       SubscriptionListener<uavcan::equipment::air_data::TrueAirspeed>::ExtendedBinder> sub_3(node);
    uavcan::Subscriber<uavcan::equipment::air_data::AngleOfAttack,
                       SubscriptionListener<uavcan::equipment::air_data::AngleOfAttack>::ExtendedBinder> sub_4(node);
    uavcan::Subscriber<uavcan::equipment::ahrs::AHRS,
                       SubscriptionListener<uavcan::equipment::ahrs::AHRS>::ExtendedBinder> sub_5(node);
    uavcan::Subscriber<uavcan::equipment::air_data::StaticPressure,
                       SubscriptionListener<uavcan::equipment::air_data::StaticPressure>::ExtendedBinder> sub_6(node);
    uavcan::Subscriber<uavcan::equipment::air_data::StaticPressure,
                       SubscriptionListener<uavcan::equipment::air_data::StaticPressure>::ExtendedBinder> sub_6_1(node);
    uavcan::ServiceServer<uavcan::protocol::file::BeginFirmwareUpdate> server(node);

    SubscriptionListener<uavcan::equipment::camera_gimbal::AngularCommand> listener_1;
    SubscriptionListener<uavcan::equipment::air_data::Sideslip> listener_2;
    SubscriptionListener<uavcan::equipment::air_data::TrueAirspeed> listener_3;
    SubscriptionListener<uavcan::equipment::air_data::AngleOfAttack> listener_4;
    SubscriptionListener<uavcan::equipment::ahrs::AHRS> listener_5;
    SubscriptionListener<uavcan::equipment::air_data::StaticPressure> listener_6;

    sub_1.start(listener_1.bindExtended());
    sub_2.start(listener_2.bindExtended());
    sub_3.start(listener_3.bindExtended());
    sub_4.start(listener_4.bindExtended());
    sub_5.start(listener_5.bindExtended());
    sub_6.start(listener_6.bindExtended());
    sub_6_1.start(listener_6.bindExtended());
    server.start(writeServiceServerCallback);
    std::cout << "Subscribers are initialized ..." << std::endl;

    uavcan::CanAcceptanceFilterConfigurator test_configurator(node);
    int configure_filters_assert = test_configurator.configureFilters();
    if (configure_filters_assert == 0)
    {
        std::cout << "Filters are configured ..." << std::endl;
    }

    const auto& configure_array = test_configurator.getConfiguration();
    uint32_t configure_array_size = configure_array.getSize();

    ASSERT_EQ(configure_filters_assert, 0);
    ASSERT_EQ(configure_array_size, 4);

    for (uint16_t i = 0; i<configure_array_size; i++)
    {
        std::cout << "config.ID [" << i << "]= " << configure_array.getByIndex(i)->id << std::endl;
        std::cout << "config.MK [" << i << "]= " << configure_array.getByIndex(i)->mask << std::endl;
    }

    ASSERT_EQ(configure_array.getByIndex(0)->id, 268435456);
    ASSERT_EQ(configure_array.getByIndex(0)->mask, 469762048);
    ASSERT_EQ(configure_array.getByIndex(1)->id, 363069440);
    ASSERT_EQ(configure_array.getByIndex(1)->mask, 536739840);
    ASSERT_EQ(configure_array.getByIndex(2)->id, 16777216);
    ASSERT_EQ(configure_array.getByIndex(2)->mask, 124452864);
    ASSERT_EQ(configure_array.getByIndex(3)->id, 18874368);
    ASSERT_EQ(configure_array.getByIndex(3)->mask, 133169152);
}
コード例 #28
0
ファイル: test.cpp プロジェクト: koshinus/CPP_programs
int _tmain(int argc, _TCHAR* argv[])
{
    std::array<std::string, 4> ar{ { "The boost::asio::buffer() function provides a convenient way "
        "to create the buffer classes, where the size of the buffer is "
        "deduced from the type possible.",
        "When Boost.Asio is able to deduce the buffer length, then Boost.",
        "The compiler expects to get an int and not an initializer-list, "
        "that's the reason for the error.",
        "The fundamental question becomes how does one know how much memory "
        "to allocate, if Boost.Asio does not transmit the size." } };
    std::string str = "The compiler expects to get an int and not an initializer-list, that's the reason for the error.";
    /*
    std::array<int, 10> ar1{ { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } };
    std::vector<std::thread> threads;
    printer pr;
    for (int i = 0; i < 4; i++)
    {
        threads.push_back(std::thread([&pr, i, &ar]()
        {
            pr.print_msg(ar[i]);
            std::chrono::milliseconds duration(500);
            std::this_thread::sleep_for(duration);
            pr.print_msg(ar[i]);
        }));
    }
    for (std::thread &t : threads)
        t.join();
    */
    try
    {
        io_service service_server;
        echo_server server(service_server);
        getline(std::cin, str);
        if (str == "1")
        {
            std::thread t1([&service_server]() { service_server.run(); });
            while (true)
            {
                getline(std::cin, str);
                if (str == "exit")
                {
                    server.stop_accept();
                    break;
                }
                io_service service_client;
                echo_client client(service_client, str);
                std::thread t2([&service_client]() { service_client.run(); });
                t2.join();
            }
            t1.join();
        }
        else
        {
            ///*
            std::thread main_thread([&service_server]() { service_server.run(); });
            while (true)
            {
                getline(std::cin, str);
                if (str == "exit")
                {
                    server.stop_accept();
                    break;
                }
                std::vector<std::unique_ptr<io_service>> clients_services;
                std::vector<std::unique_ptr<echo_client>> clients;
                std::vector<std::thread> threads;
                for (int i = 0; i < 4; i++)
                {
                    clients_services.emplace_back(new io_service());
                    //echo_client client(*clients_services[i], ar[i]);
                    clients.emplace_back(new echo_client(*clients_services[i], ar[i]));
                    threads.push_back(std::thread([i, &clients_services]() { clients_services[i]->run(); }));
                }
                for (auto & t : threads)
                    t.join();
            }
            main_thread.join();
            std::cout << "Main thread exit" << std::endl;
            //*/
        }
    }
    catch (std::exception &e)
    {
        std::cout << e.what() << std::endl;
    }

    system("pause");
    return 0;
}
コード例 #29
0
ファイル: main.cpp プロジェクト: VanessaE/minetest
/*****************************************************************************
 * Dedicated server
 *****************************************************************************/
static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
{
	verbosestream << _("Using world path") << " ["
	              << game_params.world_path << "]" << std::endl;
	verbosestream << _("Using gameid") << " ["
	              << game_params.game_spec.id << "]" << std::endl;

	// Bind address
	std::string bind_str = g_settings->get("bind_address");
	Address bind_addr(0, 0, 0, 0, game_params.socket_port);

	if (g_settings->getBool("ipv6_server")) {
		bind_addr.setAddress((IPv6AddressBytes*) NULL);
	}
	try {
		bind_addr.Resolve(bind_str.c_str());
	} catch (ResolveError &e) {
		infostream << "Resolving bind address \"" << bind_str
		           << "\" failed: " << e.what()
		           << " -- Listening on all addresses." << std::endl;
	}
	if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
		errorstream << "Unable to listen on "
		            << bind_addr.serializeString()
		            << L" because IPv6 is disabled" << std::endl;
		return false;
	}

	// Database migration
	if (cmd_args.exists("migrate"))
		return migrate_map_database(game_params, cmd_args);

	if (cmd_args.exists("migrate-players"))
		return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);

	if (cmd_args.exists("migrate-auth"))
		return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);

	if (cmd_args.exists("terminal")) {
#if USE_CURSES
		bool name_ok = true;
		std::string admin_nick = g_settings->get("name");

		name_ok = name_ok && !admin_nick.empty();
		name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);

		if (!name_ok) {
			if (admin_nick.empty()) {
				errorstream << "No name given for admin. "
					<< "Please check your minetest.conf that it "
					<< "contains a 'name = ' to your main admin account."
					<< std::endl;
			} else {
				errorstream << "Name for admin '"
					<< admin_nick << "' is not valid. "
					<< "Please check that it only contains allowed characters. "
					<< "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
					<< std::endl;
			}
			return false;
		}
		ChatInterface iface;
		bool &kill = *porting::signal_handler_killstatus();

		try {
			// Create server
			Server server(game_params.world_path, game_params.game_spec,
					false, bind_addr, true, &iface);
			server.init();

			g_term_console.setup(&iface, &kill, admin_nick);

			g_term_console.start();

			server.start();
			// Run server
			dedicated_server_loop(server, kill);
		} catch (const ModError &e) {
			g_term_console.stopAndWaitforThread();
			errorstream << "ModError: " << e.what() << std::endl;
			return false;
		} catch (const ServerError &e) {
			g_term_console.stopAndWaitforThread();
			errorstream << "ServerError: " << e.what() << std::endl;
			return false;
		}

		// Tell the console to stop, and wait for it to finish,
		// only then leave context and free iface
		g_term_console.stop();
		g_term_console.wait();

		g_term_console.clearKillStatus();
	} else {
#else
		errorstream << "Cmd arg --terminal passed, but "
			<< "compiled without ncurses. Ignoring." << std::endl;
	} {
#endif
		try {
			// Create server
			Server server(game_params.world_path, game_params.game_spec, false,
				bind_addr, true);
			server.init();
			server.start();

			// Run server
			bool &kill = *porting::signal_handler_killstatus();
			dedicated_server_loop(server, kill);

		} catch (const ModError &e) {
			errorstream << "ModError: " << e.what() << std::endl;
			return false;
		} catch (const ServerError &e) {
			errorstream << "ServerError: " << e.what() << std::endl;
			return false;
		}
	}

	return true;
}
コード例 #30
0
int main(int argc, char *argv[]) {
        enum {
                MODE_BISECT,
                MODE_CHART,
        } mode = MODE_BISECT;
        int i;
        _cleanup_free_ char *bus_name = NULL, *address = NULL;
        _cleanup_close_ int bus_ref = -1;
        cpu_set_t cpuset;
        size_t result;
        sd_bus *b;
        pid_t pid;
        int r;

        log_set_max_level(LOG_DEBUG);

        for (i = 1; i < argc; i++) {
                if (streq(argv[i], "chart")) {
                        mode = MODE_CHART;
                        continue;
                }

                assert_se(parse_sec(argv[i], &arg_loop_usec) >= 0);
        }

        assert_se(arg_loop_usec > 0);

        bus_ref = bus_kernel_create("deine-mutter", &bus_name);
        if (bus_ref == -ENOENT)
                exit(EXIT_TEST_SKIP);

        assert_se(bus_ref >= 0);

        address = strappend("kernel:path=", bus_name);
        assert_se(address);

        r = sd_bus_new(&b);
        assert_se(r >= 0);

        r = sd_bus_set_address(b, address);
        assert_se(r >= 0);

        r = sd_bus_start(b);
        assert_se(r >= 0);

        sync();
        setpriority(PRIO_PROCESS, 0, -19);

        pid = fork();
        assert_se(pid >= 0);

        if (pid == 0) {
                CPU_ZERO(&cpuset);
                CPU_SET(0, &cpuset);
                pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);

                close_nointr_nofail(bus_ref);
                sd_bus_unref(b);

                switch (mode) {
                case MODE_BISECT:
                        client_bisect(address);
                        break;

                case MODE_CHART:
                        client_chart(address);
                        break;
                }

                _exit(0);
        }

        CPU_ZERO(&cpuset);
        CPU_SET(1, &cpuset);
        pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);

        server(b, &result);

        if (mode == MODE_BISECT)
                printf("Copying/memfd are equally fast at %zu bytes\n", result);

        assert_se(waitpid(pid, NULL, 0) == pid);

        sd_bus_unref(b);

        return 0;
}