CubeSimulationWidget::CubeSimulationWidget(QWidget *parent)
  : QWidget(parent)
{
  initEnvironment(5,5,5);

  init();
}
executeIfPythonFunctionObject::executeIfPythonFunctionObject
(
    const word& name,
    const Time& t,
    const dictionary& dict
)
:
    conditionalFunctionObjectListProxy(
        name,
        t,
        dict
    ),
    pythonInterpreterWrapper(
        t.db(),
        dict
    )
{
    if(!parallelNoRun()) {
        initEnvironment(t);

        setRunTime(t);
    }

    readParameters(dict);
}
Ejemplo n.º 3
0
graph::graph(properties::iterator props) : block(properties::next(props)) {
  dbg.enterBlock(this, false, true);
  //imgPath = dbg.addImage("svg");
  maxNodeID = 0;
  
  initEnvironment();  
    
  //graphID = maxGraphID;
  graphID = properties::getInt(props, "graphID");
  
  dbg.ownerAccessing();
  dbg << "<div id=\"graph_container_"<<graphID<<"\"></div>\n";
  //dbg << "<div id=\"debug_output\"></div>\n";
  dbg.userAccessing();
  
  // If the dot encoding of the graph is already provided, emit it immediately
  if(props.exists("dotText")) {
    outputCanvizDotGraph(properties::get(props, "dotText"));
    graphOutput = true;
  // Otherwise, wait to observe the nodes and edges of the graph before emitting it in the destructor
  } else
    graphOutput = false;
  
  //cout << "Entering graphID="<<graphID<<endl;
  
  // Add the current graph to the map of ative graphs
  active[graphID] = this;
}
Ejemplo n.º 4
0
//
//  メイン関数(プログラムはここから開始)
//
int  main( int argc, char ** argv )
{
#ifdef  WIN32
	// Visual Studio 2007 のバグで、マルチバイト文字で表されたパスに日本語を含むときに、
	// ファイルを正しく開けないため、問題を回避するために、正しいロケールを設定
	locale::global( locale("japanese") );
#endif

	// GLUTの初期化
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL );
	glutInitWindowSize( 640, 640 );
	glutInitWindowPosition( 0, 0 );
    glutCreateWindow("BVH Player Sample");
	
	// コールバック関数の登録
    glutDisplayFunc( display );
    glutReshapeFunc( reshape );
	glutMouseFunc( mouse );
	glutMotionFunc( motion );
	glutKeyboardFunc( keyboard );
	glutIdleFunc( idle );

	// 環境初期化
	initEnvironment();

	// GLUTのメインループに処理を移す
    glutMainLoop();
    return 0;
}
Ejemplo n.º 5
0
void MVC_Model_Test::Init(void)
{
	MVC_Model::Init();
	srand(time(NULL));
	
	initEnvironment();
	initText();
}
Ejemplo n.º 6
0
SimBox* SimBoxBuilder::build(Box* box) {
  initEnvironment(box->environment);
  addMolecules(box->molecules, box->environment->primaryAtomIndexArray->size());
  addPrimaryIndexes(box->environment->primaryAtomIndexArray);
  if (sb->useNLC) {
    fillNLC();
  }
  return sb;
}
Ejemplo n.º 7
0
void Main::init()
{
	BallObject::init();
	initEnvironment();

	initGUI();
	
	Ball::init();
	PlayersBall::init();
}
Ejemplo n.º 8
0
void testAll () {
  initEnvironment("./");

  setAILevel(SUPREMO);

  //setAILevel(GRANDMASTER);
  //testPlayTurn();
  //testResignation();
  testDoubling();
  //testGenerateMoves();
}
Ejemplo n.º 9
0
Archivo: env.cpp Proyecto: pdhahn/occa
    envInitializer_t::envInitializer_t() :
      isInitialized(false) {
      if (isInitialized) {
        return;
      }

      initSettings();
      initEnvironment();
      registerFileOpeners();

      isInitialized = true;
    }
CubeSimulationWidget::CubeSimulationWidget(QString mapFile, AgentManagerFactory **facts,
                                           int amCount, AgentFactory **afacts,
                                           int aCount, QWidget *parent)
{
  QFile fileMap(mapFile);
  bool flag = false;


  if(fileMap.open(QFile::ReadOnly)) {
    QStringList line;

    line = QString("").append(fileMap.readLine()).split(" ");

    if(line.length() < 3)
      flag = true;
    else {
      int l, w, h;

      l = line.at(0).toInt();
      w = line.at(1).toInt();
      h = line.at(2).toInt();

      map = new Map(l,w,h);

      bool **level;
      level = new bool*[h];
      for( int i = 0; i < h; i++ )
        level[i] = new bool[w];

      QString oneLine;
      for( int i = 0; i < l; i++ ) {
        for( int j = 0; j < h; j++ ) {
          oneLine = fileMap.readLine();
          for( int k = 0; k < w; k++ )
            level[j][k] = (oneLine.at(k).toAscii() - '0');
        }
        map->loadLevelMask(i, level);
      }

      env = new Environment(map, facts, amCount, afacts, aCount);
    }
  }
  else
    flag = true;


  if(flag) {
    initEnvironment(5,5,5);
  }

  init();
}
Ejemplo n.º 11
0
int main( int argc , char **argv )
{
	char command[124] = { 0 };
	char *opt = NULL;
	int ret = 0;
	char *status = NULL;

	ret = initEnvironment();

	if( ret < 0 )
		return -1;

	createDb();

	if( argc > 1 )
	{
		opt = strtok( argv[1] , "-");

		if( !strcmp( opt , "t") )
			launchServer();
	}
	

	while( 1 )
	{
		printf("rdb~>");
		fgets( command , 124 , stdin );

		if( !strcmp("q\n" , command ) )
			break;
		else
		{
			status = ( char * )doCommand( command );
			
			if( !status )
				printf("An error occurs.\n");
			else
			{
				printf("%s\n" , status );
				zfree( status );
			}

			
		}

	}

	return 0;
}
Ejemplo n.º 12
0
/* on "init" you need to initialize your instance */
bool GameMenuScene::init()
{
    //////////////////////////////
    // 1. super init first
    if (!Layer::init()) {
            return false;
    }
    
    initEnvironment();
    initBackground();
    initMainMenu();
    initAircraft();
    
    return true;
}
timeManipulationWithPythonFunctionObject::timeManipulationWithPythonFunctionObject
(
    const word &name,
    const Time& t,
    const dictionary& dict
)
:
    timeManipulationFunctionObject(name,t,dict),
    pythonInterpreterWrapper(
        t.db(),
        dict
    )
{
    if(!parallelNoRun()) {
        initEnvironment(t);

        setRunTime(t);
    }
}
writeAndEndPythonFunctionObject::writeAndEndPythonFunctionObject
(
    const word &name,
    const Time& t,
    const dictionary& dict
)
:
    writeAndEndFunctionObject(name,t,dict),
    pythonInterpreterWrapper(
        t.db(),
        dict
    )
{
    if(!parallelNoRun()) {
        initEnvironment(t);

        setRunTime(t);
    }

    readParameters(dict);
}
Ejemplo n.º 15
0
// Sets the properties of this object
properties* mfem::setProperties(Mesh* mesh, GridFunction* soln, int widgetID, const attrOp* onoffOp, properties* props)
{
  if(props==NULL) props = new properties();
    
  // If the current attribute query evaluates to true (we're emitting debug output) AND
  // either onoffOp is not provided or its evaluates to true
  if(attributes->query() && (onoffOp? onoffOp->apply(): true)) {
    props->active = true;
    
    initEnvironment();
    
    map<string, string> newProps;
    newProps["widgetID"] = widgetID;
    newProps["meshFName"] = txt()<<htmlOutDir<<"/mfem_"<<widgetID<<".mesh";
    newProps["solnFName"] = txt()<<htmlOutDir<<"/mfem_"<<widgetID<<".soln";

    props->add("mfem", newProps);
  }
  else
    props->active = false;
  return props;
}
Ejemplo n.º 16
0
int main(int argc, char ** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
	glutInitWindowSize(g_TextureWidth, g_TextureHeight);
	glutInitWindowPosition(0, 0);
	
	win = glutCreateWindow(TITLE);
	createMenu();

	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);
	glutIdleFunc(idle);

	if (initEnvironment())
	{
		glutMainLoop();
	}

	return 0;
}
pythonIntegrationFunctionObject::pythonIntegrationFunctionObject
(
    const word& name,
    const Time& t,
    const dictionary& dict
)
:
    simpleFunctionObject(
        name,
        t,
        dict
    ),
    pythonInterpreterWrapper(
        t.db(),
        dict
    ),
    time_(t)
{
    Pbug << "Constructor" << endl;

    if(!parallelNoRun()) {
        initEnvironment(t);

        setInterpreter();
        PyObject *m = PyImport_AddModule("__main__");
        PyObject_SetAttrString(
            m,
            "functionObjectName",
            PyString_FromString(this->name().c_str())
        );
        releaseInterpreter();

        setRunTime();
    }

    read(dict);
}
int main(int argc, char ** argv)
{

    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL );
	glutInitWindowSize( 640, 640 );
	glutInitWindowPosition( 0, 0 );
    glutCreateWindow("Forward and Inverse Kinematics");
	
    glutDisplayFunc( display );
    glutReshapeFunc( reshape );
	glutMouseFunc( mouse );
	glutMotionFunc( motion );
	glutKeyboardFunc( keyboard );
#ifdef TEST_IK
	glutSpecialFunc( skeyboard );
#endif
	glutIdleFunc( idle );

	initEnvironment();

    glutMainLoop();
    return 0;
}
Ejemplo n.º 19
0
int main(int argc, char *argv[]) {
	double			pos;
    VideoState      *is;


    if(argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }

#ifdef __MINGW32__
	ptw32_processInitialize();
	//ptw32_processTerminate();
#endif

	//XInitThreads();

    is = (VideoState *)av_mallocz(sizeof(VideoState));

	avcodec_register_all();
	//avdevice_register_all();
	avfilter_register_all();
    av_register_all();
	avformat_network_init();

	if (USE_EVENT_MULTI_THREAD)
	{
		if ( SDLMOD_StartEventLoop(SDLMOD_INIT_EVENTTHREAD) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (multi thread)\n");
			exit(1);
		}
	}
	else
	{
		if ( SDLMOD_StartEventLoop(0) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (main thread)\n");
			exit(1);
		}
	}
	if (SDLMOD_TimerInit() != 0)
	{
		fprintf(stderr, "SDLMOD_TimerInit failed\n");
		exit(1);
	}

	g_video_width = 640;
	g_video_height = 480;
	g_video_resized = 0;

	//screen = SDL_SetVideoMode(g_video_width, g_video_height, SDL_VIDEO_MODE_BPP, SDL_VIDEO_MODE_FLAGS);
	screen = SDLMOD_CreateRGBSurface(0,
		g_video_width, g_video_height, SDL_VIDEO_MODE_BPP,
		Rmask, Gmask, Bmask, Amask
		);
	if(!screen) {
		fprintf(stderr, "SDL: could not set video mode - exiting\n");
		exit(1);
	}

    screen_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(screen_mutex, NULL);

    av_strlcpy(is->filename, argv[1], sizeof(is->filename));

	is->pictq_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(is->pictq_mutex, NULL);
    is->pictq_cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t));
    pthread_cond_init(is->pictq_cond, NULL);
    
	schedule_refresh(is, 40);

	is->av_sync_type = AV_SYNC_VIDEO_MASTER;

    {
		int err;
		is->parse_tid = (pthread_t *)malloc(sizeof(pthread_t));
		err = pthread_create(is->parse_tid, NULL, decodeThread, is);
		if (err!=0)
		{
			free(is->parse_tid);
			printf("can't create thread: %s\n", strerror(err));
			exit(0);
		}
	}
    if (!is->parse_tid) {
        av_free(is);
        return -1;
    }

	av_init_packet(&flush_pkt);
	flush_pkt.data = (uint8_t*)"FLUSH";

#if USE_EVENT_LOOP_MT
	{
		pthread_t pid;
		pthread_create(&pid, NULL, event_loop, is);
		if (0)
		{
			pthread_join(pid, NULL);
		}
		else
		{
#if USE_GL
			glutInit(&argc, argv);
			glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
			glutInitWindowSize(g_video_width, g_video_height);
			glutInitWindowPosition(0, 0);
			
			win = glutCreateWindow(TITLE);
			createMenu();

			glutDisplayFunc(display);
			glutReshapeFunc(reshape);
			glutMouseFunc(mouse);
			glutMotionFunc(motion);
			glutIdleFunc(idle);

			if (initEnvironment())
			{
				glutMainLoop();
			}
#else
			printf(">>>>>>Please input command (exit, quit, save):<<<<<<\n");
			char string[256];
			char* ret;
			while(1)
			{
				ret = gets(string);
				if (strcmp(string, "exit") == 0 || 
				    strcmp(string, "quit") == 0 ||
				    strcmp(string, "e") == 0 ||
				    strcmp(string, "q") == 0
				    )
				{
					break;
				}
				else if (strcmp(string, "save") == 0 ||
					strcmp(string, "s") == 0
				    )
				{
					save_bmp();
					printf("save_bmp() finish.\n");
				}
				else
				{
					printf("Please input command (exit, quit, save):\n");
				}
			}
#endif
		}
	}
#else
	event_loop(is);
#endif

    return 0;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    CApplication	app(argc, argv);
    QPixmap			pixmap(":/res/icons/app-start.png");
	QSplashScreen	*splash = NULL;
	QString			tpl = "\n          %1";
    QColor			c(0, 0, 0, 168);
    CWorkbench		*bench = NULL;

    QCoreApplication::setOrganizationName("JetMind");
    QCoreApplication::setOrganizationDomain("jetmind.com");
    QCoreApplication::setApplicationName("JetMind");

    app.setWindowIcon(QIcon(QString::fromUtf8(":/res/icons/app-logo.png")));

#if defined(__APPLE__) && defined(__MACH__)
	app.setFont( QFont("Arial", 12) );
#else
	app.setFont( QFont("Arial", 9) );
#endif //

	splash = new QSplashScreen(pixmap);
	splash->setMask(pixmap.mask());
	splash->show();
	app.processEvents();

	splash->showMessage(tpl.arg( QObject::tr("Initing Environment...") ), Qt::AlignBottom | Qt::AlignRight , c);
	app.processEvents();
	initEnvironment();

	splash->showMessage(tpl.arg( QObject::tr("Loading Templates...") ), Qt::AlignBottom | Qt::AlignRight , c);
	app.processEvents();
    loadTemplates();

	splash->showMessage(tpl.arg( QObject::tr("Starting Workbench...") ), Qt::AlignBottom | Qt::AlignRight , c);
	app.processEvents();

	bench = new CWorkbench();
    bench->setWindowTitle("JetMind");
	bench->resize(800, 600);
	bench->show();
    bench->loadStyleSheet();
	app.setWorkbench(bench);
	CDiagramContext::env()->setMainUI(bench);

	splash->finish(bench);

	// set url handler
	QDesktopServices::setUrlHandler("topic", (QObject*)bench, "onOpenUrl");
	QDesktopServices::setUrlHandler("sheet", (QObject*)bench, "onOpenUrl");

#if defined(__APPLE__) && defined(__MACH__)
    bench->createFile();
#else
	QStringList args;
	args = app.arguments();
	if (args.length() > 1)
	{
		bench->loadFile(args.at(1));
	}
	else
	{
		bench->createFile();
	}
#endif //

	return app.exec();
}
Ejemplo n.º 21
0
Mparse::Mparse()
{

    markedContext = v8::Context::New();
    initEnvironment();
}
Ejemplo n.º 22
0
AppScript::AppScript()
{
    markedContext = v8::Context::New();
    initEnvironment();
}
Ejemplo n.º 23
0
/** Main function to start the env node. */
int main(int argc, char *argv[])
{
  ros::init(argc, argv, NODE);
  ros::NodeHandle node;

  if (argc < 2){
    cout << "--env type  option is required" << endl;
    displayHelp();
    exit(-1);
  }

  // env and seed are required
  if (argc < 3){
    displayHelp();
    exit(-1);
  }

  // parse options to change these parameters
  envType = argv[1];
  seed = std::atoi(argv[2]);

  // parse env type first
  bool gotEnv = false;
  for (int i = 1; i < argc-1; i++){
    if (strcmp(argv[i], "--env") == 0){
      gotEnv = true;
      envType = argv[i+1];
    }
  }
  if (!gotEnv) {
    cout << "--env type  option is required" << endl;
    displayHelp();
  }

  // now parse other options
  char ch;
  const char* optflags = "ds:";
  int option_index = 0;
  static struct option long_options[] = {
    {"env", 1, 0, 'e'},
    {"deterministic", 0, 0, 'd'},
    {"stochastic", 0, 0, 's'},
    {"delay", 1, 0, 'a'},
    {"nsectors", 1, 0, 'c'},
    {"nstocks", 1, 0, 't'},
    {"lag", 0, 0, 'l'},
    {"nolag", 0, 0, 'o'},
    {"seed", 1, 0, 'x'},
    {"prints", 0, 0, 'p'},
    {"highvar", 0, 0, 'v'}
  };

  while(-1 != (ch = getopt_long_only(argc, argv, optflags, long_options, &option_index))) {
    switch(ch) {

    case 'x':
      seed = std::atoi(optarg);
      cout << "seed: " << seed << endl;
      break;

    case 'd':
      stochastic = false;
      cout << "stochastic: " << stochastic << endl;
      break;

    case 'v':
      {
        if (strcmp(envType, "fuelworld") == 0){
          highvar = true;
          cout << "fuel world fuel cost variation: " << highvar << endl;
        } else {
          cout << "--highvar is only a valid option for the fuelworld domain." << endl;
          exit(-1);
        }
        break;
      }

    case 's':
      stochastic = true;
      cout << "stochastic: " << stochastic << endl;
      break;

    case 'a':
      {
        if (strcmp(envType, "mcar") == 0 || strcmp(envType, "tworooms") == 0){
          delay = std::atoi(optarg);
          cout << "delay steps: " << delay << endl;
        } else {
          cout << "--delay option is only valid for the mcar and tworooms domains" << endl;
          exit(-1);
        }
        break;
      }

    case 'c':
      {
        if (strcmp(envType, "stocks") == 0){
          nsectors = std::atoi(optarg);
          cout << "nsectors: " << nsectors << endl;
        } else {
          cout << "--nsectors option is only valid for the stocks domain" << endl;
          exit(-1);
        }
        break;
      }
    
    case 't':
      {
        if (strcmp(envType, "stocks") == 0){
          nstocks = std::atoi(optarg);
          cout << "nstocks: " << nstocks << endl;
        } else {
          cout << "--nstocks option is only valid for the stocks domain" << endl;
          exit(-1);
        }
        break;
      }
      
    case 'l':
      {
        if (strcmp(envType, "car2to7") == 0 || strcmp(envType, "car7to2") == 0 || strcmp(envType, "carrandom") == 0){
          lag = true;
          cout << "lag: " << lag << endl;
        } else {
          cout << "--lag option is only valid for car velocity tasks" << endl;
          exit(-1);
        }
        break;
      }

    case 'o':
       {
         if (strcmp(envType, "car2to7") == 0 || strcmp(envType, "car7to2") == 0 || strcmp(envType, "carrandom") == 0){
           lag = false;
           cout << "lag: " << lag << endl;
         } else {
           cout << "--nolag option is only valid for car velocity tasks" << endl;
           exit(-1);
         }
         break;
       }

    case 'e':
      // already processed this one
      cout << "env: " << envType << endl;
      break;

    case 'p':
      PRINTS = true;
      break;

    case 'h':
    case '?':
    case 0:
    default:
      displayHelp();
      break;
    }
  }


  int qDepth = 1;

  // Set up Publishers
  ros::init(argc, argv, "my_tf_broadcaster");
  tf::Transform transform;

  // Set up Publishers
  out_env_desc = node.advertise<rl_msgs::RLEnvDescription>("rl_env/rl_env_description",qDepth,true);
  out_env_sr = node.advertise<rl_msgs::RLStateReward>("rl_env/rl_state_reward",qDepth,false);
  out_seed = node.advertise<rl_msgs::RLEnvSeedExperience>("rl_env/rl_seed",20,false);

  // Set up subscribers
  ros::TransportHints noDelay = ros::TransportHints().tcpNoDelay(true);
  ros::Subscriber rl_action =  node.subscribe("rl_agent/rl_action", qDepth, processAction, noDelay);
  ros::Subscriber rl_exp_info =  node.subscribe("rl_agent/rl_experiment_info", qDepth, processEpisodeInfo, noDelay);

  // publish env description, first state
  // Setup RL World
  rng = Random(1+seed);
  initEnvironment();


  ROS_INFO(NODE ": starting main loop");
  
  ros::spin();                          // handle incoming data
  //while (ros::ok()){
  //  ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(0.1));
  //}

  return 0;
}
Ejemplo n.º 24
0
int main(int argc, const char *argv[])
{
    poptContext optCon;   /* context for parsing command-line options */

    int rc, version = 0, debugMask = 0, pipeFD[2] = {-1, -1}, magic = FORKMAGIC;
    char *logdest = NULL, *configfile = "/etc/parastation.conf";
    FILE *logfile = NULL;

    struct poptOption optionsTable[] = {
	{ "debug", 'd', POPT_ARG_INT, &debugMask, 0,
	  "enable debugging with mask <mask>", "mask"},
	{ "configfile", 'f', POPT_ARG_STRING, &configfile, 0,
	  "use <file> as config-file (default is /etc/parastation.conf)",
	  "file"},
	{ "logfile", 'l', POPT_ARG_STRING, &logdest, 0,
	  "use <file> for logging (default is syslog(3))."
	  " <file> may be 'stderr' or 'stdout'", "file"},
	{ "version", 'v', POPT_ARG_NONE, &version, 0,
	  "output version information and exit", NULL},
	POPT_AUTOHELP
	{ NULL, '\0', 0, NULL, 0, NULL, NULL}
    };

    optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
    rc = poptGetNextOpt(optCon);

    /* Store arguments for later modification in forwarders, etc. */
    PSID_argc = argc;
    PSID_argv = argv;

    if (version) {
	printVersion();
	return 0;
    }

    if (logdest) {
	if (strcasecmp(logdest, "stderr")==0) {
	    logfile = stderr;
	} else if (strcasecmp(logdest, "stdout")==0) {
	    logfile = stdout;
	} else {
	    logfile = fopen(logdest, "a+");
	    if (!logfile) {
		char *errstr = strerror(errno);
		fprintf(stderr, "Cannot open logfile '%s': %s\n", logdest,
			errstr ? errstr : "UNKNOWN");
		exit(1);
	    }
	}
    }

    if (!logfile) {
	openlog("psid", LOG_PID|LOG_CONS, LOG_DAEMON);
    }
    PSID_initLogs(logfile);

    printWelcome();

    if (rc < -1) {
	/* an error occurred during option processing */
	poptPrintUsage(optCon, stderr, 0);
	PSID_log(-1, "%s: %s\n",
		 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		 poptStrerror(rc));
	if (!logfile)
	    fprintf(stderr, "%s: %s\n",
		    poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		    poptStrerror(rc));

	return 1;
    }

    /* Save some space in order to modify the cmdline later on */
    PSC_saveTitleSpace(PSID_argc, PSID_argv, 1);

    if (logfile!=stderr && logfile!=stdout) {
	/* Daemonize only if neither stdout nor stderr is used for logging */
	if (pipe(pipeFD) < 0) {
	    PSID_exit(errno, "unable to create pipe");
	}

	/* Start as daemon */
	switch (fork()) {
	case -1:
	    PSID_exit(errno, "unable to fork server process");
	    break;
	case 0: /* I'm the child (and running further) */
	    close (pipeFD[0]);
	    break;
	default: /* I'm the parent and exiting */
	    close (pipeFD[1]);

	    /* Wait for child's magic data */
	    rc = read(pipeFD[0], &magic, sizeof(magic));
	    if (rc != sizeof(magic) || magic != (FORKMAGIC)) return -1;

	    return 0;
       }
    }

#define _PATH_TTY "/dev/tty"
    /* First disconnect from the old controlling tty. */
    {
	int fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
	if (fd >= 0) {
	    if (ioctl(fd, TIOCNOTTY, NULL)) {
		PSID_warn(-1, errno, "%s: ioctl(TIOCNOTTY)", __func__);
	    }
	    close(fd);
	}
    }


    /*
     * Disable stdin,stdout,stderr and install dummy replacement
     * Take care if stdout/stderr is used for logging
     */
    {
	int dummy_fd;

	dummy_fd=open("/dev/null", O_WRONLY , 0);
	dup2(dummy_fd, STDIN_FILENO);
	if (logfile!=stdout) dup2(dummy_fd, STDOUT_FILENO);
	if (logfile!=stderr) dup2(dummy_fd, STDERR_FILENO);
	close(dummy_fd);
    }

    /* Forget about inherited window sizes */
    unsetenv("LINES");
    unsetenv("COLUMNS");

    if (debugMask) {
	PSID_setDebugMask(debugMask);
	PSC_setDebugMask(debugMask);
	PSID_log(-1, "Debugging mode (mask 0x%x) enabled\n", debugMask);
    }

    /* Init the Selector facility as soon as possible */
    if (!Selector_isInitialized()) Selector_init(logfile);
    PSID_registerLoopAct(Selector_gc);

    /* Initialize timer facility explicitely to ensure correct logging */
    if (!Timer_isInitialized()) Timer_init(logfile);

    /*
     * Create the Local Service Port as early as possible. Actual
     * handling is enabled later. This gives psiadmin the chance to
     * connect. Additionally, this will guarantee exclusiveness
     */
    PSID_createMasterSock(PSmasterSocketName);

    PSID_checkMaxPID();

    /* read the config file */
    PSID_readConfigFile(logfile, configfile);
    /* Now we can rely on the config structure */

    {
	in_addr_t addr;

	PSID_log(-1, "My ID is %d\n", PSC_getMyID());

	addr = PSIDnodes_getAddr(PSC_getMyID());
	PSID_log(-1, "My IP is %s\n", inet_ntoa(*(struct in_addr *) &addr));
    }

    if (!logfile && PSID_config->logDest!=LOG_DAEMON) {
	PSID_log(-1, "Changing logging dest from LOG_DAEMON to %s\n",
		 PSID_config->logDest==LOG_KERN ? "LOG_KERN":
		 PSID_config->logDest==LOG_LOCAL0 ? "LOG_LOCAL0" :
		 PSID_config->logDest==LOG_LOCAL1 ? "LOG_LOCAL1" :
		 PSID_config->logDest==LOG_LOCAL2 ? "LOG_LOCAL2" :
		 PSID_config->logDest==LOG_LOCAL3 ? "LOG_LOCAL3" :
		 PSID_config->logDest==LOG_LOCAL4 ? "LOG_LOCAL4" :
		 PSID_config->logDest==LOG_LOCAL5 ? "LOG_LOCAL5" :
		 PSID_config->logDest==LOG_LOCAL6 ? "LOG_LOCAL6" :
		 PSID_config->logDest==LOG_LOCAL7 ? "LOG_LOCAL7" :
		 "UNKNOWN");
	closelog();

	openlog("psid", LOG_PID|LOG_CONS, PSID_config->logDest);
	printWelcome();
    }

    /* call startupScript, if any */
    if (PSID_config->startupScript && *PSID_config->startupScript) {
	int ret = PSID_execScript(PSID_config->startupScript, NULL, NULL, NULL);

	if (ret > 1) {
	    PSID_log(-1, "startup script '%s' failed. Exiting...\n",
		     PSID_config->startupScript);
	    PSID_finalizeLogs();
	    exit(1);
	}
    }

    /* Setup handling of signals */
    initSigHandlers();

    if (PSID_config->coreDir) {
	if (chdir(PSID_config->coreDir) < 0) {
	    PSID_warn(-1, errno, "Unable to chdir() to coreDirectory '%s'",
		      PSID_config->coreDir);
	}
    }

    PSIDnodes_setProtoV(PSC_getMyID(), PSProtocolVersion);
    PSIDnodes_setDmnProtoV(PSC_getMyID(), PSDaemonProtocolVersion);
    PSIDnodes_setHWStatus(PSC_getMyID(), 0);
    PSIDnodes_setKillDelay(PSC_getMyID(), PSID_config->killDelay);
    PSIDnodes_setAcctPollI(PSC_getMyID(), PSID_config->acctPollInterval);

    /* Bring node up with correct numbers of CPUs */
    declareNodeAlive(PSC_getMyID(), PSID_getPhysCPUs(), PSID_getVirtCPUs());

    /* Initialize timeouts, etc. */
    PSID_initStarttime();

    /* initialize various modules */
    PSIDcomm_init();  /* This has to be first since it gives msgHandler hash */

    PSIDclient_init();
    initState();
    initOptions();
    initStatus();
    initSignal();
    PSIDspawn_init();
    initPartition();
    initHW();
    initAccount();
    initInfo();
    initEnvironment();
    /* Plugins shall be last since they use most of the ones before */
    initPlugins();

    /* Now we start all the hardware -- this might include the accounter */
    PSID_log(PSID_LOG_HW, "%s: starting up the hardware\n", __func__);
    PSID_startAllHW();

    /*
     * Prepare hostlist to initialize RDP and MCast
     */
    {
	in_addr_t *hostlist;
	int i;

	hostlist = malloc(PSC_getNrOfNodes() * sizeof(unsigned int));
	if (!hostlist) {
	    PSID_exit(errno, "Failed to get memory for hostlist");
	}

	for (i=0; i<PSC_getNrOfNodes(); i++) {
	    hostlist[i] = PSIDnodes_getAddr(i);
	}

	if (PSID_config->useMCast) {
	    /* Initialize MCast */
	    int MCastSock = initMCast(PSC_getNrOfNodes(),
				      PSID_config->MCastGroup,
				      PSID_config->MCastPort,
				      logfile, hostlist,
				      PSC_getMyID(), MCastCallBack);
	    if (MCastSock<0) {
		PSID_exit(errno, "Error while trying initMCast");
	    }
	    setDeadLimitMCast(PSID_config->deadInterval);

	    PSID_log(-1, "MCast and ");
	} else {
	    setStatusTimeout(PSID_config->statusTimeout);
	    setMaxStatBCast(PSID_config->statusBroadcasts);
	    setDeadLimit(PSID_config->deadLimit);
	    setTmOutRDP(PSID_config->RDPTimeout);
	}

	/* Initialize RDP */
	RDPSocket = RDP_init(PSC_getNrOfNodes(),
			     PSIDnodes_getAddr(PSC_getMyID()),
			     PSID_config->RDPPort, logfile, hostlist,
			     PSIDRDP_handleMsg, RDPCallBack);
	if (RDPSocket<0) {
	    PSID_exit(errno, "Error while trying initRDP");
	}

	PSID_log(-1, "RDP (%d) initialized.\n", RDPSocket);

	free(hostlist);
    }

    /* Now start to listen for clients */
    PSID_enableMasterSock();

    /* Once RDP and the master socket are ready parents might be released */
    if (pipeFD[1] > -1) {
	if (write(pipeFD[1], &magic, sizeof(magic)) <= 0) {
	    /* We don't care */
	}
	close(pipeFD[1]);
    }

    PSID_log(-1, "SelectTime=%d sec    DeadInterval=%d\n",
	     PSID_config->selectTime, PSID_config->deadInterval);

    /* Trigger status stuff, if necessary */
    if (PSID_config->useMCast) {
	declareMaster(PSC_getMyID());
    } else {
	int id = 0;
	while (id < PSC_getMyID()
	       && (send_DAEMONCONNECT(id) < 0 && errno == EHOSTUNREACH)) {
	    id++;
	}
	if (id == PSC_getMyID()) declareMaster(id);
    }

    /*
     * Main loop
     */
    while (1) {
	int res = Swait(PSID_config->selectTime * 1000);

	if (res < 0) PSID_warn(-1, errno, "Error while Swait()");

	/* Handle actions registered to main-loop */
	PSID_handleLoopActions();
    }
}