示例#1
0
void InitializeMessageChannels (VLMConfig* config)
{
  EmbPtr cp = EmbCommAreaAlloc (sizeof (EmbMessageChannel));
  register EmbMessageChannel *p = (EmbMessageChannel*) HostPointer (cp);
  register EmbCommandChannel *cc;

	p->type = EmbMessageChannelType;
	p->unit = 0;
	EmbCommAreaPtr->command_channel = cp;
	p->next = EmbCommAreaPtr->channel_table;	/* Link into the channel list */
	EmbCommAreaPtr->channel_table = cp;

	p->subtype = EmbMessageChannelCommandSubtype;
	p->hostToGuestQueue = NullEmbPtr;			/* Should never be used ... */
	p->hostToGuestSupplyQueue = NullEmbPtr;		/* ... */

	cc = malloc (sizeof (EmbCommandChannel));
	if (NULL == cc) vpunt (NULL, "Couldn't allocate master command message channel");
	SetSubtypeData (p, cc);

	cc->header.nextActiveChannel = NULL;
	cc->header.commArea = EmbCommAreaPtr;
	cc->header.messageChannel = p;

	p->guestToHostQueue = CreateQueue (CommandQueueSize, sizeof (EmbPtr));
	cc->guestToHostQueue = (EmbQueue*) HostPointer (p->guestToHostQueue);
	cc->guestToHostQueue->signal = InstallSignalHandler ((ProcPtrV) &ExecuteGuestCommands, 
														 (PtrV) cc, FALSE);
	
	p->guestToHostReturnQueue = CreateQueue (CommandQueueSize, sizeof (EmbPtr));
	cc->guestToHostReturnQueue = (EmbQueue*) HostPointer (p->guestToHostReturnQueue);
}
示例#2
0
文件: joyd.c 项目: mmitch/joyd
int main (int argc, char **argv)
/* simple main program */
{
	/* don't tell me that this condition looks ugly... */
	if (    (argc > 2)
	     || (
                   (argc == 2)
                && (
                      (strcmp(argv[1],PRINT_VERSION)      == 0)
		   || (strcmp(argv[1],PRINT_VERSION_LONG) == 0)
		   )
                 )
           ) {
		printf(PROGRAM_VERSION "\n");
		printf(PROGRAM_INFOTEXT "\n");
		exit(0);
	};

	SetDefaultValues();

	if (config.debug > 1) {
		Print(stdout,PROGRAM_VERSION," starting up");
	}

	InstallSignalHandler();

	if (argc > 1) {
		free(config.config_file);
		config.config_file = AllocString(argv[1]);
	}
	
	ReadConfigFile();

	if (config.daemon) {
		ForkToBackground();
	}
	
	OpenJoystick();

	AddMissingCalibrations();

	ActionLoop();

	CloseJoystick();

	Print(stdout,PROGRAM_VERSION," quits now (should've never come around here!?)");

	return 0;
}
int main( int argc, const char** argv )
{
    ParseOptions(argc, argv);
    ConvertCrLf = (strcmp(ConvertCrLfStr, "on") == 0);

    OpenSerialPort(&SerialPort, SP_MODE_READ|SP_MODE_WRITE);

    InstallSignalHandler();

    EventLoop();

    sp_close(SerialPort);
    sp_free_port(SerialPort);
    return 0;
}
示例#4
0
void ExecuteGuestCommands (EmbCommandChannel *commandChannel)
{
  register EmbQueue *commandQueue = commandChannel->guestToHostQueue;
  register EmbQueue *resultsQueue = commandChannel->guestToHostReturnQueue;
  EmbPtr commandPtr;
  register EmbCommandBuffer *command;
  EmbCommandStartMBINBuffer *startMBINCommand;
  EmbMessageChannel *mbinChannel;
  EmbMBINChannel *mbinSubChannel;

	while (EmbQueueFilled (commandQueue))
	  {
		if (0 == EmbQueueSpace (resultsQueue))
		  {
			SignalLater (commandQueue->signal);
			return;
		  }

		commandPtr = EmbQueueTakeWord (commandQueue);
		if (commandPtr)
		  {
			command = (EmbCommandBuffer*) HostPointer (commandPtr);

			switch (command->header.opcode)
			{
			  case EmbCommandBufferStartMBIN:
				/* Activate an MBIN channel that was created by the VLM */
				startMBINCommand = (EmbCommandStartMBINBuffer*) command;
				mbinChannel = (EmbMessageChannel*) HostPointer (startMBINCommand->mbinChannel);
				mbinSubChannel = malloc (sizeof (EmbMBINChannel));
				if (NULL == mbinSubChannel)
					command->resultCode = ENOMEM;
				else
				  {
					mbinSubChannel->header.commArea = EmbCommAreaPtr;
					mbinSubChannel->header.messageChannel = mbinChannel;
					mbinSubChannel->guestToHostQueue
					  = (EmbQueue*) HostPointer (mbinChannel->guestToHostQueue);
					mbinSubChannel->guestToHostReturnQueue
					  = (EmbQueue*) HostPointer (mbinChannel->guestToHostReturnQueue);
					mbinSubChannel->hostToGuestQueue
					  = (EmbQueue*) HostPointer (mbinChannel->hostToGuestQueue);
					mbinSubChannel->hostToGuestSupplyQueue
					  = (EmbQueue*) HostPointer (mbinChannel->hostToGuestSupplyQueue);
					SetSubtypeData (mbinChannel, mbinSubChannel);
					ThreadActiveMessageChannel ((EmbMessageChannel*) mbinChannel);
					activeMBINChannel = mbinSubChannel;
					mbinSubChannel->guestToHostQueue->signal
					  = InstallSignalHandler((ProcPtrV)&SendMBINBuffers, (PtrV)mbinSubChannel,
											 FALSE);
					command->resultCode = ESUCCESS;
				  }
				break;

			  default:
				/* Unrecognized opcode */
				command->resultCode = EINVAL;
			}

			EmbQueuePutWord (resultsQueue, commandPtr);
		  }
	  }
}
示例#5
0
// Usage: process-wrapper
//            <timeout_sec> <kill_delay_sec> <stdout file> <stderr file>
//            [cmdline]
int main(int argc, char *argv[]) {
  if (argc <= 5) {
    DIE("Not enough cmd line arguments to process-wrapper");
  }

  // Parse the cmdline args to get the timeout and redirect files.
  argv++;
  double timeout;
  if (sscanf(*argv++, "%lf", &timeout) != 1) {
    DIE("timeout_sec is not a real number.");
  }
  if (sscanf(*argv++, "%lf", &global_kill_delay) != 1) {
    DIE("kill_delay_sec is not a real number.");
  }
  char *stdout_path = *argv++;
  char *stderr_path = *argv++;

  if (strcmp(stdout_path, "-")) {
    // Redirect stdout and stderr.
    int fd_out = open(stdout_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd_out == -1) {
      DIE("Could not open %s for stdout", stdout_path);
    }
    if (dup2(fd_out, STDOUT_FILENO) == -1) {
      DIE("dup2 failed for stdout");
    }
    CHECK_CALL(close(fd_out));
  }

  if (strcmp(stderr_path, "-")) {
    int fd_err = open(stderr_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd_err == -1) {
      DIE("Could not open %s for stderr", stderr_path);
    }
    if (dup2(fd_err, STDERR_FILENO) == -1) {
      DIE("dup2 failed for stderr");
    }
    CHECK_CALL(close(fd_err));
  }

  global_pid = fork();
  if (global_pid < 0) {
    DIE("Fork failed");
  } else if (global_pid == 0) {
    // In child.
    if (setsid() == -1) {
      DIE("Could not setsid from child");
    }
    ClearSignalMask();
    // Force umask to include read and execute for everyone, to make
    // output permissions predictable.
    umask(022);

    execvp(argv[0], argv);  // Does not return.
    DIE("execvpe %s failed", argv[0]);
  } else {
    // In parent.
    InstallSignalHandler(SIGALRM);
    InstallSignalHandler(SIGTERM);
    InstallSignalHandler(SIGINT);
    EnableAlarm(timeout);

    int status = WaitChild(global_pid, argv[0]);

    // The child is done, but may have grandchildren.
    kill(-global_pid, SIGKILL);
    if (global_signal > 0) {
      // Don't trust the exit code if we got a timeout or signal.
      UnHandle(global_signal);
      raise(global_signal);
    } else if (WIFEXITED(status)) {
      exit(WEXITSTATUS(status));
    } else {
      int sig = WTERMSIG(status);
      UnHandle(sig);
      raise(sig);
    }
  }
}
示例#6
0
文件: main.cpp 项目: miguelinux/vbox
extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char ** /*envp*/)
{
#ifdef RT_OS_WINDOWS
    ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
#endif

    /* Failed result initially: */
    int iResultCode = 1;

    /* Start logging: */
    LogFlowFuncEnter();

    /* Simulate try-catch block: */
    do
    {
#ifdef VBOX_WS_MAC
        /* Hide setuid root from AppKit: */
        HideSetUidRootFromAppKit();
#endif /* VBOX_WS_MAC */

#ifdef VBOX_WS_X11
        /* Make sure multi-threaded environment is safe: */
        if (!MakeSureMultiThreadingIsSafe())
            break;
#endif /* VBOX_WS_X11 */

        /* Console help preprocessing: */
        bool fHelpShown = false;
        for (int i = 0; i < argc; ++i)
        {
            if (   !strcmp(argv[i], "-h")
                || !strcmp(argv[i], "-?")
                || !strcmp(argv[i], "-help")
                || !strcmp(argv[i], "--help"))
            {
                fHelpShown = true;
                ShowHelp();
                break;
            }
        }
        if (fHelpShown)
        {
            iResultCode = 0;
            break;
        }

#ifdef VBOX_WITH_HARDENING
        /* Make sure the image verification code works: */
        SUPR3HardenedVerifyInit();
#endif /* VBOX_WITH_HARDENING */

#ifdef VBOX_WS_MAC
        /* Apply font fixes (before QApplication get created and instantiated font-hints): */
        switch (VBoxGlobal::determineOsRelease())
        {
            case MacOSXRelease_Mavericks: QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); break;
            case MacOSXRelease_Yosemite:  QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Helvetica Neue"); break;
            case MacOSXRelease_ElCapitan: QFont::insertSubstitution(".SF NS Text", "Helvetica Neue"); break;
            default: break;
        }

        /* Instantiate own NSApplication before QApplication do it for us: */
        UICocoaApplication::instance();
#endif /* VBOX_WS_MAC */

#ifdef VBOX_WS_X11
# if defined(RT_OS_LINUX) && defined(DEBUG)
        /* Install signal handler to backtrace the call stack: */
        InstallSignalHandler();
# endif /* RT_OS_LINUX && DEBUG */
#endif /* VBOX_WS_X11 */

#if QT_VERSION >= 0x050000
        /* Install Qt console message handler: */
        qInstallMessageHandler(QtMessageOutput);
#else /* QT_VERSION < 0x050000 */
        /* Install Qt console message handler: */
        qInstallMsgHandler(QtMessageOutput);
#endif /* QT_VERSION < 0x050000 */

        /* Create application: */
        QApplication a(argc, argv);

#ifdef VBOX_WS_WIN
        /* Drag in the sound drivers and DLLs early to get rid of the delay taking
         * place when the main menu bar (or any action from that menu bar) is
         * activated for the first time. This delay is especially annoying if it
         * happens when the VM is executing in real mode (which gives 100% CPU
         * load and slows down the load process that happens on the main GUI
         * thread to several seconds). */
        PlaySound(NULL, NULL, 0);
#endif /* VBOX_WS_WIN */

#ifdef VBOX_WS_MAC
# ifdef VBOX_GUI_WITH_HIDPI
        /* Enable HiDPI icons.
         * For this we require a patched version of Qt 4.x with
         * the changes from https://codereview.qt-project.org/#change,54636 applied. */
        a.setAttribute(Qt::AA_UseHighDpiPixmaps);
# endif /* VBOX_GUI_WITH_HIDPI */

        /* Disable menu icons on MacOS X host: */
        ::darwinDisableIconsInMenus();
#endif /* VBOX_WS_MAC */

#ifdef VBOX_WS_X11
        /* Make all widget native.
         * We did it to avoid various Qt crashes while testing widget attributes or acquiring winIds.
         * Yes, we aware of note that alien widgets faster to draw but the only widget we need to be fast
         * is viewport of VM which was always native since we are using his id for 3D service needs. */
        a.setAttribute(Qt::AA_NativeWindows);

# ifdef Q_OS_SOLARIS
#  if QT_VERSION < 0x050000
        /* Use plastique look&feel for Solaris instead of the default motif (Qt 4.7.x): */
        QApplication::setStyle(new QPlastiqueStyle);
#  else /* QT_VERSION >= 0x050000 */
	a.setStyle("fusion");
#  endif /* QT_VERSION >= 0x050000 */
# endif /* Q_OS_SOLARIS */

# ifndef Q_OS_SOLARIS
        /* Apply font fixes (after QApplication get created and instantiated font-family): */
        QFontDatabase fontDataBase;
        QString currentFamily(QApplication::font().family());
        bool isCurrentScaleable = fontDataBase.isScalable(currentFamily);
        QString subFamily(QFont::substitute(currentFamily));
        bool isSubScaleable = fontDataBase.isScalable(subFamily);
        if (isCurrentScaleable && !isSubScaleable)
#  if QT_VERSION >= 0x050000
            QFont::removeSubstitutions(currentFamily);
#  else /* QT_VERSION < 0x050000 */
            QFont::removeSubstitution(currentFamily);
#  endif /* QT_VERSION < 0x050000 */
# endif /* !Q_OS_SOLARIS */

        /* Qt version check (major.minor are sensitive, fix number is ignored): */
        if (VBoxGlobal::qtRTVersion() < (VBoxGlobal::qtCTVersion() & 0xFFFF00))
        {
            QString strMsg = QApplication::tr("Executable <b>%1</b> requires Qt %2.x, found Qt %3.")
                                              .arg(qAppName())
                                              .arg(VBoxGlobal::qtCTVersionString().section('.', 0, 1))
                                              .arg(VBoxGlobal::qtRTVersionString());
            QMessageBox::critical(0, QApplication::tr("Incompatible Qt Library Error"),
                                  strMsg, QMessageBox::Abort, 0);
            qFatal("%s", strMsg.toUtf8().constData());
            break;
        }
#endif /* VBOX_WS_X11 */

        /* Create modal-window manager: */
        UIModalWindowManager::create();

        /* Create global UI instance: */
        VBoxGlobal::create();

        /* Simulate try-catch block: */
        do
        {
            /* Exit if VBoxGlobal is not valid: */
            if (!vboxGlobal().isValid())
                break;

            /* Exit if VBoxGlobal pre-processed arguments: */
            if (vboxGlobal().processArgs())
                break;

            /* For Runtime UI: */
            if (vboxGlobal().isVMConsoleProcess())
            {
                /* Prevent application from exiting when all window(s) closed: */
                qApp->setQuitOnLastWindowClosed(false);
            }

            /* Request to Show UI _after_ QApplication started: */
            QMetaObject::invokeMethod(&vboxGlobal(), "showUI", Qt::QueuedConnection);

            /* Start application: */
            iResultCode = a.exec();
        }
        while (0);

        /* Destroy global UI instance: */
        VBoxGlobal::destroy();

        /* Destroy modal-window manager: */
        UIModalWindowManager::destroy();
    }
    while (0);

    /* Finish logging: */
    LogFlowFunc(("rc=%d\n", iResultCode));
    LogFlowFuncLeave();

    /* Return result: */
    return iResultCode;
}
示例#7
0
int main(int argc, char *argv[])
{
  Entity et;
  int error, startupflags, i;
  char *restartname, name[128];
#ifdef PARALLEL
  const ParCommand end = EXIT;
#endif
  InitVarTable();
#ifdef PARALLEL
  IsMaster();
  if (master) {
    printf("MetPhoMod   Rel. 2.2\n" SYSTEM " parallel Version - " DATE "\n\n");
#else
  printf("MetPhoMod   Rel. 2.2\n" SYSTEM " sequential Version - " DATE "\n\n");
#endif
    if (argc > 1 && (!strcmp(argv[1], "-help") || !strcmp(argv[1], "-h")))  {
      McInterface::modmanager.Init1();
      PrintHelp(argc - 2, argv + 2);
      exit (0);
    }
    if (argc > 1 && !strcmp(argv[1], "-genchem"))  {
      if (argc != 3)  goto instant_help;
      GenerateSpecialChem(argv[2]);
      exit (0);
    }
    startupflags = AnalizeOptions(&argc, argv, &restartname);
    if (argc != 2)  {
instant_help :
      printf("Usage : meteochem [-RESTART restart-file [-REOPEN]] [-noexcpt] [-syntax] \\\n"
             "                  [-nooutput] [-debug] [-sequential] inpfile\n"
             "or    : meteochem (-h | -help) [keyword]\n"
             "or    : meteochem -genchem chemfile\n");
      return (1);
    }
    McInterface::modmanager.Init1();
    if (startupflags & SYNTAX_ONLY)  {
      if (ParseInput(argv[1]))  {
        printf("Errors in Input-File\n");
        return (1);
      }
      else  {
        printf("the input-file seems to be OK!\n");
        return (0);
      }
    }
#ifdef PARALLEL
    if (startupflags & SEQUENTIAL)  {
      parallel = FALSE; master = TRUE;
      leftest = rightest = TRUE;
    }
  }
  if (master)  {
#endif
    if (ParseInput(argv[1]))  {
      fprintf(stderr, "Errors parsing Input-File. I don't start the calculation.\n");
      return (1);
    }
    plausible = TRUE;
    if (!(startupflags & NOEXCPT))  InstallFpeHandler();
    tinc = chemtinc = tincmax;
    actime = chemtime = tstart;
#ifdef PARALLEL
    if (!parallel)  printf("\n\n!!! Using sequential mode !!!\n\n");
    else
      McInterface::modmanager.CheckIfReadyForParallel();
  }
  InitializeWorkers(argv[0], startupflags & DEBUG_WORKERS);
  if (parallel && !master)  {
    if (!(startupflags & NOEXCPT))  InstallFpeHandler();
    McInterface::modmanager.Init1();
    ReadDataFromMaster();
    InitializeData();
    plausible = TRUE;
    tinc = chemtinc = tincmax;
    actime = chemtime = tstart;
  }
  if (parallel && master)  {
    printf("Sending Data to workers...\n");
    SendDataToWorkers();
    InitializeData();
  }
  if (!parallel)
#endif
    InitializeData();
  for (et = maxentity; et--; )
    if (g[et])
      CalculateLayerAverage(g[et], pstat, avg+et*nz);
    else
      memset(avg+et*nz, 0, nz*sizeof(double));
  CalcMeanHydrostaticPressure();
#ifdef PARALLEL
  if (!parallel || !master)  {
#endif
    SetAvgMountains();
    SetBoundary(maxentity);
/*    CalcAllKm();  */
#ifdef PARALLEL
  }
  if (parallel && !master)  {
    if (GetRestartName(name))  {
      if (!(ReadFullDump(name, (startupflags & REOPEN)) && actime <= tend))  {
	printf("Error : Restart-file not found\n");
	plausible = FALSE;
      }
    }
  }
  else  {
    if (parallel)
      SendRestartName((startupflags & RESTART) ? restartname : NULL);
#endif
    if (startupflags & RESTART)  {
      if (!ReadFullDump(restartname, (startupflags & REOPEN)))  {
        printf("Error : Restart-file not found\n");
        return (1);
      }
    }
    else if (startupflags & REOPEN)  {
      printf("Error: -REOPEN can only be used together with -RESTART\n");
      return (1);
    }
#ifdef PARALLEL
  }
  if (master)  {
#endif
    if (!(startupflags & NO_OUTPUT))  {
      printf("Opening output-Files...");
      if (OpenOutputFiles(argv[1], (startupflags & RESTART) && (startupflags & REOPEN)))  {
        printf("\nExecution abortet\n");
        exit (1);
      }
      CreateDomainFiles((startupflags & RESTART) && (startupflags & REOPEN));
    }
    InstallSignalHandler();
    printf("\n");
#ifdef PARALLEL
    if (parallel)  printf("Starting calculation...\n");
  }
#else  
  printf("Starting calculation...\n");
#endif
#if PARALLEL
  if (!parallel || master)  
#endif
    if (!(startupflags & NO_OUTPUT))  {
      WriteOutData(tstart, FALSE);
      WriteToDomainFiles(tstart);
    }
/*  TestChemicals("Start");  */
#if PARALLEL
  if (parallel)
    if (master)  MastersLoop(startupflags);
    else	 WorkersLoop(startupflags);
  else
#endif
    SequentialLoop(startupflags);
  printf("Closing output-Files...\n");
  if (plausible)  printf("Calculation terminated successfully\n\n");
  else  {
    if (!(startupflags & NO_OUTPUT))
      WriteOutData(actime, TRUE);
    printf("Calculation stopped because of inplausibilities!\n\n");
  }
  if (!(startupflags & NO_OUTPUT))  {
    CloseOutputFiles();
    CloseDomainFiles();
  }
#ifdef PARALLEL
  if (parallel)  {
    pvm_initsend(PvmDataRaw);
    pvm_pkint((int *)&end, 1, 1);
    SendCommand();
    pvm_exit();
  }
#endif
  return (0);
}