コード例 #1
0
/*****************************************************************************
 * NAME: exec_clrbdblks
 *
 * FUNCTION:	Start clrbblks in a child process and wait for it to complete.
 *
 * PARAMETERS:  none
 *
 * NOTES:	
 *
 * RETURNS:
 *      success: FSCK_OK
 *      failure: something else
 */
retcode_t exec_clrbdblks( )
{
  retcode_t ec_rc = FSCK_OK;
  CHAR szFailName[CCHMAXPATH];
  RESULTCODES resc;
  CHAR szCommandLine[] = "clrbblks\0\0\0\0\0\0\0\0\0\0\0\0";
	
  memcpy((void *) &(szCommandLine[9]), (void *) Vol_Label, sizeof(Vol_Label));
	
  ec_rc = DosExecPgm( szFailName,   sizeof(szFailName),
                                 EXEC_SYNC,
                                 szCommandLine, (PSZ) NULL,
                                 &resc, "clrbblks.exe" );
	/*
	 * log the result of the DosExecPgm
	 */
  sprintf( message_parm_0, "%ld", ec_rc );
  msgprms[0] = message_parm_0;
  msgprmidx[0] = 0;
  fsck_send_msg( fsck_DOSEXECPGMRC, 0, 1 );
	/*
	 * if the DosExecPgm was successful, log and
	 * return the result of the clrbblks process
	 */
  if( ec_rc == 0 ) {
    sprintf( message_parm_0, "%ld,%ld", resc.codeTerminate, resc.codeResult );
    msgprms[0] = message_parm_0;
    msgprmidx[0] = 0;
    fsck_send_msg( fsck_CLRBBLKSRC, 0, 1 );
    ec_rc = resc.codeResult + resc.codeTerminate;
    }
	
  return( ec_rc );
}                            /* end of exec_clrbdblks()  */
コード例 #2
0
ファイル: cachef32.c プロジェクト: OS2World/DRV-FAT32
BOOL ChkDsk(ULONG ulBootDisk, PSZ pszDisk)
{
APIRET rc;
static BYTE szObjName[255];
static BYTE szProgram[255] = "X:\\OS2\\CHKDSK.COM";
static BYTE szArguments[512];
RESULTCODES Res;


   szProgram[0] = (BYTE)(ulBootDisk + '@');
   memset(szArguments, 0, sizeof szArguments);
   strcpy(szArguments, szProgram);
   sprintf(szArguments + strlen(szArguments) + 1,
      "%s /F /C", pszDisk);
      

   rc = DosExecPgm(szObjName, sizeof szObjName,
      EXEC_SYNC,
      szArguments,
      NULL,
      &Res,
      szProgram);
   if (rc)
      {
      printf("DosExecPgm Failed, rc = %d\n", rc);
      return FALSE;
      }
   return TRUE;   
}
コード例 #3
0
static void LoadProg( char *cmd, char *cmd_tail )
{
    RESULTCODES         res;
    NEWSTARTDATA        start;
    USHORT              SID;

    if( NewSession ) {
        start.Length = 50;
        start.Related = 1;
        start.FgBg = 0;
        start.TraceOpt = 1;
        start.PgmTitle = cmd;
        start.PgmName = cmd;
        start.PgmInputs = (PBYTE)cmd_tail;
        start.TermQ = 0;
        start.Environment = NULL;
        start.InheritOpt = 1;
        start.SessionType = 0;
        start.IconFile = NULL;
        start.PgmHandle = 0;
        start.PgmControl = 0;
        if( DosStartSession( (void __far *)&start, &SID, &Pid ) != 0 ) {
            InternalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
        }
    } else {
        if( DosExecPgm( NULL, 0, EXEC_TRACE, cmd, NULL, &res, cmd ) != 0 ) {
            InternalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
        }
        Pid = res.codeTerminate;
    }
}
コード例 #4
0
ファイル: mpmt_os2.c プロジェクト: kheradmand/Break
static void spawn_child(int slot)
{
    PPIB ppib;
    PTIB ptib;
    char fail_module[100];
    char progname[CCHMAXPATH];
    RESULTCODES proc_rc;
    ULONG rc;

    ap_scoreboard_image->parent[slot].generation = ap_my_generation;
    DosGetInfoBlocks(&ptib, &ppib);
    DosQueryModuleName(ppib->pib_hmte, sizeof(progname), progname);
    rc = DosExecPgm(fail_module, sizeof(fail_module), EXEC_ASYNCRESULT,
                    ppib->pib_pchcmd, NULL, &proc_rc, progname);

    if (rc) {
        ap_log_error(APLOG_MARK, APLOG_ERR, APR_FROM_OS_ERROR(rc), ap_server_conf,
                     "error spawning child, slot %d", slot);
    }

    if (ap_max_daemons_limit < slot) {
        ap_max_daemons_limit = slot;
    }

    ap_scoreboard_image->parent[slot].pid = proc_rc.codeTerminate;
}
コード例 #5
0
ファイル: cachef32.c プロジェクト: OS2World/DRV-FAT32
BOOL StartMe(PSZ pszPath)
{
APIRET rc;
static BYTE szObjName[255];
static BYTE szArguments[512];
RESULTCODES Res;

   memset(szArguments, 0, sizeof szArguments);
   strcpy(szArguments, pszPath);
   sprintf(szArguments + strlen(szArguments) + 1,
      " /P:%u", pOptions->bLWPrio);

   rc = DosExecPgm(szObjName, sizeof szObjName,
      EXEC_BACKGROUND,
      szArguments,
      NULL,
      &Res,
      pszPath);
   if (rc)
      {
      printf("FAT32: unable to start deamon (%s)\n. rc = %d for %s\n",
         szArguments, rc, szObjName);
      return FALSE;
      }
   printf("FAT32: Lazy write daemon started.\n");
   return TRUE;   
}
コード例 #6
0
ファイル: os2conv.c プロジェクト: Azarien/open-watcom-v2
/*
 * get the address of Dos32Debug, and get the flat selectors, too.
 */
int GetDos32Debug( char __far *err )
{
    char        buff[256];
    RESULTCODES resc;
    USHORT      dummy;
    PSZ         start;
    PSZ         p;
    HFILE       inh;
    HFILE       outh;
    USHORT      rc;
    struct {
        ULONG       dos_debug;
        USHORT      cs;
        USHORT      ds;
        USHORT      ss;
    }           data;

    rc = DosGetModName( ThisDLLModHandle, sizeof( buff ), buff );
    if( rc ) {
        StrCopy( TRP_OS2_no_dll, err );
        return( FALSE );
    }
    start = buff;
    for( p = buff; *p != '\0'; ++p ) {
        switch( *p ) {
        case ':':
        case '\\':
        case '/':
           start = p + 1;
           break;
        }
    }
    p = StrCopy( LOCATOR, start );
    if( DosMakePipe( &inh, &outh, sizeof( data ) ) ) {
        StrCopy( TRP_OS2_no_pipe, err );
        return( FALSE );
    }
    *++p = outh + '0';
    *++p = '\0';
    *++p = '\0';
    rc = DosExecPgm( NULL, 0, EXEC_ASYNC, buff, NULL, &resc, buff );
    DosClose( outh );
    if( rc )  {
        DosClose( inh );
        StrCopy( TRP_OS2_no_help, err );
        return( FALSE );
    }
    rc = DosRead( inh, &data, sizeof( data ), &dummy );
    DosClose( inh );
    if( rc ) {
        StrCopy( TRP_OS2_no_help, err );
        return( FALSE );
    }
    DebugFunc = (void __far *)data.dos_debug;
    FlatCS = (USHORT) data.cs;
    FlatDS = (USHORT) data.ds;

    _retaddr = MakeLocalPtrFlat( (void __far *)DoReturn );
    return( TRUE );
}
コード例 #7
0
int main(void)
{
    APIRET apiret;
    HPIPE hpipe;
    PSZ pipeName = "\\pipe\\testpipe";
    PSZ semName = "\\sem32\\pipesem";
    HEV hev;
    CHAR objname[50];
    RESULTCODES rc;
    ULONG bytesread;
    CHAR buf[50];

    printf(__FILE__ " main function invoked\n");
    printf("Test named pipe functions\n");

    apiret = DosCreateNPipe(pipeName, &hpipe, 0, NP_WAIT, 0, 0, 0);
    printf("DosCreateNPipe function returned %d\n", (int)apiret);

    apiret = DosCreateEventSem(semName, &hev, DC_SEM_SHARED, FALSE);
    printf("DosCreateEventSem function returned %d\n", (int)apiret);

    apiret = DosExecPgm(objname, 50, EXEC_ASYNC, NULL, NULL, &rc, "./test11a");
    printf("DosExecPgm function returned %d\n", (int)apiret);

    apiret = DosWaitEventSem(hev, 5000);
    printf("DosWaitEventSem function returned %d\n", (int)apiret);

    apiret = DosRead((HFILE)hpipe, buf, sizeof(buf) - 1, &bytesread);
    printf("DosRead function returned %d\n", (int)apiret);
    buf[bytesread] = '\0';
    printf("Message was \"%s\"\n", buf);

    apiret = DosWaitEventSem(hev, 5000);
    printf("DosWaitEventSem function returned %d\n", (int)apiret);

    apiret = DosRead((HFILE)hpipe, buf, sizeof(buf) - 1, &bytesread);
    printf("DosRead function returned %d\n", (int)apiret);
    buf[bytesread] = '\0';
    printf("Message was \"%s\"\n", buf);

    apiret = DosWaitEventSem(hev, 5000);
    printf("DosWaitEventSem function returned %d\n", (int)apiret);

    apiret = DosRead((HFILE)hpipe, buf, sizeof(buf) - 1, &bytesread);
    printf("DosRead function returned %d\n", (int)apiret);
    buf[bytesread] = '\0';
    printf("Message was \"%s\"\n", buf);

    /* wait for test11a to catch up with us */
    DosSleep(2000);

    apiret = DosCloseEventSem(hev);
    printf("DosCloseEventSem function returned %d\n", (int)apiret);

    apiret = DosClose((HFILE)hpipe);
    printf("DosClose function returned %d\n", (int)apiret);

    return 0;
}
コード例 #8
0
/****************************************************************\
 *  Initialization routine
 *--------------------------------------------------------------
 *
 *  Name:   Init()
 *
 *  Purpose: Performs initialization functions.
 *
 *  Usage:  Called once before the message queue is queried.
 *
 *  Method:
 *          - starts processing thread
 *          - registers all window classes
 *
 *  Returns:
 *          TRUE  - initialization is successful
 *          FALSE - initialization failed
\****************************************************************/
BOOL Init(int argc, char *argv[])
{
   PTIB   ptibDummy;
   PIB    *ppibProcess;
   ULONG  flCtlData;    /* frame control data */


   /* load application name from resource file */
   if(!WinLoadString(hab, NULLHANDLE, IDS_APPNAME, MAXNAMEL, (PSZ)szAppName))
      return FALSE;

   /* register the main client window class */
   if(!WinRegisterClass(hab,
                        (PSZ)szAppName,
                        MainWndProc,
                        CS_SIZEREDRAW | CS_CLIPCHILDREN,
                        0UL))
   {
      return FALSE;
   }

   flCtlData = FCF_STANDARD | FCF_VERTSCROLL | FCF_HORZSCROLL;

   hwndMainFrame = WinCreateStdWindow(HWND_DESKTOP,
                                      WS_VISIBLE,
                                      &flCtlData,
                                      (PSZ)szAppName,
                                      (PSZ)NULL,
                                      WS_VISIBLE,
                                      NULLHANDLE,
                                      IDR_MAIN,
                                      &hwndMain);
   if (NULLHANDLE == hwndMainFrame)
      return FALSE;

   WinSetWindowText(hwndMainFrame, (PSZ)szAppName);

   if (DosGetInfoBlocks(&ptibDummy, &ppibProcess) ||
       !(hqQ = InitQ((*ppibProcess).pib_ulpid,  /* process that will send WM_CLOSE command */
                     hwndMainFrame)))           /* window to post to */
      return FALSE;

   if (argc > 1)
   {
      RESULTCODES  resc;
      CHAR  pszBuff[CCHMAXPATH];

      if ((BOOL)DosExecPgm((PSZ)pszBuff, CCHMAXPATH, EXEC_ASYNC, NULL, NULL, &resc, argv[1]))
      {
         MessageBox(hwndMain, IDMSG_CANNOT_EXEC_CLIENT, MB_CUAWARNING | MB_OK, TRUE);
      }
   }

   InitHelp();

   return TRUE;
}  /* Init() */
コード例 #9
0
static int run(char* command)
{
	int rc = 0;
	char* parm = 0;

	RESULTCODES rcl = {0};

	if(!command || !command[0])
		return 2;	//ERROR_FILE_NOT_FOUND

	int len = strlen(command);

	parm = new char[len + 2];

	parm[len + 1] = 0;

	strcpy(parm, command);

	do
	{
		char* str;
		char* beg = parm;

		while(*beg && __issp(*beg))
			beg++;

		if(!*beg)
		{
			rc = 2;
			break;
		}

		str = beg;

		if(*str == '"')
		{
			while(*str && *str != '"')
				str++;
		}
		else
		{
			while(*str && !__issp(*str))
				str++;
		}
		*str = 0;

		rc = DosExecPgm(0, 0, EXEC_ASYNCRESULT, (PSZ)parm, 0, &rcl, (PSZ)parm);
	}
	while(0);

	delete parm;

	return rc;
}
コード例 #10
0
 int main(VOID) {

 UCHAR       LoadError[CCHMAXPATH] = {0};

 PSZ         Args             = NULL;

 PSZ         Envs             = NULL;

 RESULTCODES ChildRC          = {0};

 APIRET      rc               = NO_ERROR;  /* Return code */



   rc = DosExecPgm(LoadError,           /* Object name buffer           */

                   sizeof(LoadError),   /* Length of object name buffer */

                   EXEC_SYNC,           /* Asynchronous/Trace flags     */

                   Args,                /* Argument string              */

                   Envs,                /* Environment string           */

                   &ChildRC,            /* Termination codes            */

                   "qfsinfo.exe");      /* Program file name            */



   if (rc != NO_ERROR) {

      printf("DosExecPgm error: return code = %u\n",rc);

      return 1;

   } else {

      printf("DosExecPgm complete.  Termination Code: %u  Return Code: %u\n",

              ChildRC.codeTerminate,

              ChildRC.codeResult);  /* This is explicitly set by other pgm */

   } /* endif */



   return NO_ERROR;

   }
コード例 #11
0
ファイル: lxapid_cmd.c プロジェクト: OS2World/DRV-LXAPI32
//------------------------------- CMD_DosExecPgm -------------------------------
void CMD_DosExecPgm(HFILE hFile,LXIOCPA_DMN_CMDPARMPACKET* pParam
                    ,PLXDOSEXECPGMSTRUCT p)
{
 char *pArg=0;
 char *pEnv=0;
 if(p->arglen)
 {
  pArg=(char*)(((unsigned long)p)+sizeof(LXDOSEXECPGMSTRUCT));
 }
 if(p->envlen)
  pEnv=(char*)(((unsigned long)p)+p->arglen+sizeof(LXDOSEXECPGMSTRUCT));
 pParam->rc=DosExecPgm(p->objname,p->cbObjname,p->execFlag,pArg,pEnv
                      ,&(p->res),p->name);
}
コード例 #12
0
/*---------------------------------------------------------------------------
                                  CmdSpawn
---------------------------------------------------------------------------*/
void CmdSpawn( WNDATTR *wndattr )
{
  char args[CCHMAXPATHCOMP + 4];
  int len;
  RESULTCODES result;

   len = strlen( _argv[0] ) + 1;
   memcpy( args, _argv[0], len );
   memcpy( args + len, "-i\0", 4 );

   DosExecPgm( NULL, 0, EXEC_ASYNC,
               args, NULL, &result, _argv[0] );

   return;
}
コード例 #13
0
ファイル: os2.c プロジェクト: axelmuhr/Helios-NG
execprog( char *cmd)
{
	char		 args[NSTRING];		/* args passed to program */
	char		*sp;
	char		 failName[NFILEN];
	char		 prog[NSTRING];		/* name of program */
	USHORT		 i;
	PRESULTCODES	 results;
	

	/*
	 * Parse the command name from the command line and copy it
	 * into the prog and args arrays.
	 */
	i = 0;
	while (cmd[i]  &&  (cmd[i] != ' ')  &&  (cmd[i] != '\t')) {
		prog[i] = args[i] = cmd[i];
		i++;
	}
	prog[i] = args[i] = 0;		/* terminate with a null */

	/* skip whitespace and copy the args */
	while (cmd[i]  &&  ((cmd[i] == ' ')  ||  (cmd[i] == '\t')))
		i++;
	while (cmd[i]) {
		args[i] = cmd[i];
		i++;
	}
	args[i] = args[i + 1] = 0;	/* terminate with 2 nulls */
	
	
	/* look up the program on the path, trying various extentions */
	if ((sp = flook(prog, TRUE)) == NULL)
		if ((sp = flook(strcat(prog, ".exe"), TRUE)) == NULL) {
			strcpy(&prog[strlen(prog)-4], ".com");
			if ((sp = flook(prog, TRUE)) == NULL)
				return(FALSE);
		}
	strcpy(prog, sp);

	/*
	 * Execute the program synchronously.  We wait for child
	 * to return.
	 */
	return (0 == DosExecPgm( failName, NFILEN, EXEC_SYNC,
					 args, 0, results, prog));
}
コード例 #14
0
/*
    If we're running on OS/2 2.x and it's an LX style file, spawn off the
    OS/2 2.x sampler to collect things
*/
bool VersionCheck( void )
{
    USHORT          env_sel;
    USHORT          cmd_off;
    RESULTCODES     res;

    DosGetVersion( &OSVer );
    if( OSVer >= 0x1400 && IsLX() ) {
        if( DosSearchPath( 0x0003, "PATH", OS22SAMPLER, (unsigned char *)UtilBuff, sizeof( UtilBuff ) ) ) {
            InternalError( MsgArray[MSG_SAMPLE_8 - ERR_FIRST_MESSAGE] );
        }
        DosGetEnv( &env_sel, &cmd_off );
        if( DosExecPgm( NULL, 0, EXEC_ASYNC, MK_FP( env_sel, cmd_off ), NULL, &res, UtilBuff ) != 0 ) {
            InternalError( MsgArray[MSG_SAMPLE_9 - ERR_FIRST_MESSAGE] );
        }
        _exit( 0 );
    }
    return( OSVer >= 0x0a14 );
}
コード例 #15
0
VOID Installer_ExecuteScript( VOID )
{
 // Задаем приложение и команду для него.
 CHAR Rexx_script[ SIZE_OF_PATH ] = "";
 strcpy( Rexx_script, Installer_Thread.Current_directory );
 strcat( Rexx_script, "\\Install\\Script.cmd" );

 // Проверяем существование приложения.
 if( !FileExists( Rexx_script ) ) return;

 // Запускаем приложение.
 {
  CHAR Rexx_parameters[ SIZE_OF_PATH ] = "";

  if( Installer_Thread.Install_Enhancer ) strcat( Rexx_parameters, " --action=install" );
  if( Installer_Thread.Uninstall_Enhancer ) strcat( Rexx_parameters, " --action=uninstall" );
  if( Installer.Code_page == RUSSIAN ) strcat( Rexx_parameters, " --language=russian" );

  {
   CHAR Rexx_launcher[] = "Cmd.exe";
   CHAR Launcher_parameters[ SIZE_OF_PATH ] = "";

   strcpy( Launcher_parameters, Rexx_launcher );   strcat( Launcher_parameters, "|" );
   strcat( Launcher_parameters, "/C" );            strcat( Launcher_parameters, " \"" );
   strcat( Launcher_parameters, Rexx_script );     strcat( Launcher_parameters, " " );
   strcat( Launcher_parameters, Rexx_parameters ); strcat( Launcher_parameters, "\"" );
   strchg( Launcher_parameters, '|', 0x00 );

   CHAR Error_string[ 1 ] = ""; RESULTCODES Return_codes;
   CHAR Path[ SIZE_OF_PATH ] = "";
   strcpy( Path, Installer_Thread.Current_directory );
   strcat( Path, "\\Install" );

   DosSetCurrentDir( Path );
   DosResetBuffer( -1 ); DosExecPgm( Error_string, sizeof( Error_string ), EXEC_SYNC, Launcher_parameters, NULL, &Return_codes, Rexx_launcher );
   DosSetCurrentDir( Installer_Thread.Current_directory );
  }
 }

 // Возврат.
 return;
}
コード例 #16
0
ファイル: minicmd.c プロジェクト: ErisBlastar/osfree
void execute_external(int argc, char **argv)
{
  UCHAR       LoadError[255];
  PSZ         Args;
  PSZ         Envs;
  RESULTCODES ChildRC;
  APIRET      rc;  /* Return code */
  char        *env;
  int         i;

  log("execute_external():\n");
  log("argc=%d\n", argc);

  for (i = 0; i < argc; i++)
    log("argv[%d]=%s\n", i, argv[i]);

  env = env_get();

  rc = DosExecPgm(LoadError,           /* Object name buffer           */
                  sizeof(LoadError),   /* Length of object name buffer */
                  EXEC_SYNC,           /* Asynchronous/Trace flags     */
                  argv[0],             /* Argument string              */
                  env,                 /* Environment string           */
                  &ChildRC,            /* Termination codes            */
                  argv[0]);            /* Program file name            */

  env_free(env);

  if (rc != NO_ERROR) {
//     printf("DosExecPgm error: return code = %u\n",rc);
     VioWrtTTY("DosExecPgm error\r\n", 18, 0); //: return code = %u\n",rc);
     return ;
  } else {
//     printf("DosExecPgm complete.  Termination Code: %u  Return Code: %u\n",
//             ChildRC.codeTerminate,
//             ChildRC.codeResult);  /* This is explicitly set by other pgm */
  } /* endif */
}
コード例 #17
0
static void RunCmd( char *cmd_name )
{
    char        cmd[MAX_TRANS+80];
    RESULTCODES res;
    UINT        rc;

    //NYI: spawning of DOS and PM programs
    //DOS programs can be handled by quoting the redirection
    //operators:
    //          prog 1^>out 2^>&1
    sprintf( cmd, "%s%c/C %s 0<NUL 1>%s 2>&1%c", CmdProc, 0, cmd_name, RedirName, 0 );
    rc = DosExecPgm( NULL, 0,           /* don't care about fail name */
                EXEC_ASYNCRESULT,       /* execflags */
                cmd,                    /* args */
                NULL,                   /* inherit environment */
                &res,                   /* result codes */
                CmdProc );              /* pgmname */
    if( rc == 0 ) {
        ProcId = res.codeTerminate;
    } else {
        ProcId = 0;
    }
}
コード例 #18
0
ファイル: os2misc.c プロジェクト: ppbao/mozilla-os2
PRProcess * _PR_CreateOS2Process(
    const char *path,
    char *const *argv,
    char *const *envp,
    const PRProcessAttr *attr)
{
    PRProcess *proc = NULL;
    char *cmdLine = NULL;
    char **newEnvp = NULL;
    char *envBlock = NULL;
   
    STARTDATA startData = {0};
    APIRET    rc;
    ULONG     ulAppType = 0;
    PID       pid = 0;
    char     *pszComSpec;
    char      pszEXEName[CCHMAXPATH] = "";
    char      pszFormatString[CCHMAXPATH];
    char      pszObjectBuffer[CCHMAXPATH];
    char     *pszFormatResult = NULL;

    /*
     * Variables for DosExecPgm
     */
    char szFailed[CCHMAXPATH];
    char *pszCmdLine = NULL;
    RESULTCODES procInfo;
    HFILE hStdIn  = 0,
          hStdOut = 0,
          hStdErr = 0;
    HFILE hStdInSave  = -1,
          hStdOutSave = -1,
          hStdErrSave = -1;

    proc = PR_NEW(PRProcess);
    if (!proc) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        goto errorExit;
    }
   
    if (assembleCmdLine(argv, &cmdLine) == -1) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        goto errorExit;
    }

#ifdef MOZ_OS2_HIGH_MEMORY
    /*
     * DosQueryAppType() fails if path (the char* in the first argument) is in
     * high memory. If that is the case, the following moves it to low memory.
     */ 
    if ((ULONG)path >= 0x20000000) {
        size_t len = strlen(path) + 1;
        char *copy = (char *)alloca(len);
        memcpy(copy, path, len);
        path = copy;
    }
#endif
   
    if (envp == NULL) {
        newEnvp = NULL;
    } else {
        int i;
        int numEnv = 0;
        while (envp[numEnv]) {
            numEnv++;
        }
        newEnvp = (char **) PR_MALLOC((numEnv+1) * sizeof(char *));
        for (i = 0; i <= numEnv; i++) {
            newEnvp[i] = envp[i];
        }
        qsort((void *) newEnvp, (size_t) numEnv, sizeof(char *), compare);
    }
    if (assembleEnvBlock(newEnvp, &envBlock) == -1) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        goto errorExit;
    }
  
    rc = DosQueryAppType(path, &ulAppType);
    if (rc != NO_ERROR) {
       char *pszDot = strrchr(path, '.');
       if (pszDot) {
          /* If it is a CMD file, launch the users command processor */
          if (!stricmp(pszDot, ".cmd")) {
             rc = DosScanEnv("COMSPEC", (PSZ *)&pszComSpec);
             if (!rc) {
                strcpy(pszFormatString, "/C %s %s");
                strcpy(pszEXEName, pszComSpec);
                ulAppType = FAPPTYP_WINDOWCOMPAT;
             }
          }
       }
    }
    if (ulAppType == 0) {
       PR_SetError(PR_UNKNOWN_ERROR, 0);
       goto errorExit;
    }
 
    if ((ulAppType & FAPPTYP_WINDOWAPI) == FAPPTYP_WINDOWAPI) {
        startData.SessionType = SSF_TYPE_PM;
    }
    else if (ulAppType & FAPPTYP_WINDOWCOMPAT) {
        startData.SessionType = SSF_TYPE_WINDOWABLEVIO;
    }
    else {
        startData.SessionType = SSF_TYPE_DEFAULT;
    }
 
    if (ulAppType & (FAPPTYP_WINDOWSPROT31 | FAPPTYP_WINDOWSPROT | FAPPTYP_WINDOWSREAL))
    {
        strcpy(pszEXEName, "WINOS2.COM");
        startData.SessionType = PROG_31_STDSEAMLESSVDM;
        strcpy(pszFormatString, "/3 %s %s");
    }
 
    startData.InheritOpt = SSF_INHERTOPT_SHELL;
 
    if (pszEXEName[0]) {
        pszFormatResult = PR_MALLOC(strlen(pszFormatString)+strlen(path)+strlen(cmdLine));
        sprintf(pszFormatResult, pszFormatString, path, cmdLine);
        startData.PgmInputs = pszFormatResult;
    } else {
        strcpy(pszEXEName, path);
        startData.PgmInputs = cmdLine;
    }
    startData.PgmName = pszEXEName;
 
    startData.Length = sizeof(startData);
    startData.Related = SSF_RELATED_INDEPENDENT;
    startData.ObjectBuffer = pszObjectBuffer;
    startData.ObjectBuffLen = CCHMAXPATH;
    startData.Environment = envBlock;
 
    if (attr) {
        /* On OS/2, there is really no way to pass file handles for stdin,
         * stdout, and stderr to a new process.  Instead, we can make it
         * a child process and make the given file handles a copy of our
         * stdin, stdout, and stderr.  The child process then inherits
         * ours, and we set ours back.  Twisted and gross I know. If you
         * know a better way, please use it.
         */
        if (attr->stdinFd) {
            hStdIn = 0;
            DosDupHandle(hStdIn, &hStdInSave);
            DosDupHandle((HFILE) attr->stdinFd->secret->md.osfd, &hStdIn);
        }

        if (attr->stdoutFd) {
            hStdOut = 1;
            DosDupHandle(hStdOut, &hStdOutSave);
            DosDupHandle((HFILE) attr->stdoutFd->secret->md.osfd, &hStdOut);
        }

        if (attr->stderrFd) {
            hStdErr = 2;
            DosDupHandle(hStdErr, &hStdErrSave);
            DosDupHandle((HFILE) attr->stderrFd->secret->md.osfd, &hStdErr);
        }
        /*
         * Build up the Command Line for DosExecPgm
         */
        pszCmdLine = PR_MALLOC(strlen(pszEXEName) +
                               strlen(startData.PgmInputs) + 3);
        sprintf(pszCmdLine, "%s%c%s%c", pszEXEName, '\0',
                startData.PgmInputs, '\0');
        rc = DosExecPgm(szFailed,
                        CCHMAXPATH,
                        EXEC_ASYNCRESULT,
                        pszCmdLine,
                        envBlock,
                        &procInfo,
                        pszEXEName);
        PR_DELETE(pszCmdLine);

        /* Restore our old values.  Hope this works */
        if (hStdInSave != -1) {
            DosDupHandle(hStdInSave, &hStdIn);
            DosClose(hStdInSave);
        }

        if (hStdOutSave != -1) {
            DosDupHandle(hStdOutSave, &hStdOut);
            DosClose(hStdOutSave);
        }

        if (hStdErrSave != -1) {
            DosDupHandle(hStdErrSave, &hStdErr);
            DosClose(hStdErrSave);
        }

        if (rc != NO_ERROR) {
            /* XXX what error code? */
            PR_SetError(PR_UNKNOWN_ERROR, rc);
            goto errorExit;
        }

        proc->md.pid = procInfo.codeTerminate;
    } else {	
        /*
         * If no STDIN/STDOUT redirection is not needed, use DosStartSession
         * to create a new, independent session
         */
        rc = DosStartSession(&startData, &ulAppType, &pid);

        if ((rc != NO_ERROR) && (rc != ERROR_SMG_START_IN_BACKGROUND)) {
            PR_SetError(PR_UNKNOWN_ERROR, rc);
            goto errorExit;
        }
 
        proc->md.pid = pid;
    }

    if (pszFormatResult) {
        PR_DELETE(pszFormatResult);
    }

    PR_DELETE(cmdLine);
    if (newEnvp) {
        PR_DELETE(newEnvp);
    }
    if (envBlock) {
        PR_DELETE(envBlock);
    }
    return proc;

errorExit:
    if (cmdLine) {
        PR_DELETE(cmdLine);
    }
    if (newEnvp) {
        PR_DELETE(newEnvp);
    }
    if (envBlock) {
        PR_DELETE(envBlock);
    }
    if (proc) {
        PR_DELETE(proc);
    }
    return NULL;
}  /* _PR_CreateOS2Process */
コード例 #19
0
/**
 * Daemonize the process for running in the background.
 *
 * This is supposed to do the same job as the BSD daemon() call.
 *
 * @returns 0 on success
 *
 * @param   fNoChDir    Pass false to change working directory to root.
 * @param   fNoClose    Pass false to redirect standard file streams to /dev/null.
 * @param   fRespawn    Restart the daemonised process after five seconds if it
 *                      terminates abnormally.
 * @param   pcRespawn   Where to store a count of how often we have respawned,
 *                      intended for avoiding error spamming.  Optional.
 *
 * @todo    Use RTProcDaemonize instead of this.
 * @todo    Implement fRespawn on OS/2.
 * @todo    Make the respawn interval configurable.  But not until someone
 *          actually needs that.
 */
VBGLR3DECL(int) VbglR3Daemonize(bool fNoChDir, bool fNoClose, bool fRespawn, unsigned *pcRespawn)
{
#if defined(RT_OS_OS2)
    PPIB pPib;
    PTIB pTib;
    DosGetInfoBlocks(&pTib, &pPib);

    AssertRelease(!fRespawn);
    /* Get the full path to the executable. */
    char szExe[CCHMAXPATH];
    APIRET rc = DosQueryModuleName(pPib->pib_hmte, sizeof(szExe), szExe);
    if (rc)
        return RTErrConvertFromOS2(rc);

    /* calc the length of the command line. */
    char *pch = pPib->pib_pchcmd;
    size_t cch0 = strlen(pch);
    pch += cch0 + 1;
    size_t cch1 = strlen(pch);
    pch += cch1 + 1;
    char *pchArgs;
    if (cch1 && *pch)
    {
        do  pch = strchr(pch, '\0') + 1;
        while (*pch);

        size_t cchTotal = pch - pPib->pib_pchcmd;
        pchArgs = (char *)alloca(cchTotal + sizeof("--daemonized\0\0"));
        memcpy(pchArgs, pPib->pib_pchcmd, cchTotal - 1);
        memcpy(pchArgs + cchTotal - 1, "--daemonized\0\0", sizeof("--daemonized\0\0"));
    }
    else
    {
        size_t cchTotal = pch - pPib->pib_pchcmd + 1;
        pchArgs = (char *)alloca(cchTotal + sizeof(" --daemonized "));
        memcpy(pchArgs, pPib->pib_pchcmd, cch0 + 1);
        pch = pchArgs + cch0 + 1;
        memcpy(pch, " --daemonized ", sizeof(" --daemonized ") - 1);
        pch += sizeof(" --daemonized ") - 1;
        if (cch1)
            memcpy(pch, pPib->pib_pchcmd + cch0 + 1, cch1 + 2);
        else
            pch[0] = pch[1] = '\0';
    }

    /* spawn a detach process  */
    char szObj[128];
    RESULTCODES ResCodes = { 0, 0 };
    szObj[0] = '\0';
    rc = DosExecPgm(szObj, sizeof(szObj), EXEC_BACKGROUND, (PCSZ)pchArgs, NULL, &ResCodes, (PCSZ)szExe);
    if (rc)
    {
        /** @todo Change this to some standard log/print error?? */
        /* VBoxServiceError("DosExecPgm failed with rc=%d and szObj='%s'\n", rc, szObj); */
        return RTErrConvertFromOS2(rc);
    }
    DosExit(EXIT_PROCESS, 0);
    return VERR_GENERAL_FAILURE;

#elif defined(RT_OS_WINDOWS)
# error "PORTME"

#else /* the unices */
    /*
     * Fork the child process in a new session and quit the parent.
     *
     * - fork once and create a new session (setsid). This will detach us
     *   from the controlling tty meaning that we won't receive the SIGHUP
     *   (or any other signal) sent to that session.
     * - The SIGHUP signal is ignored because the session/parent may throw
     *   us one before we get to the setsid.
     * - When the parent exit(0) we will become an orphan and re-parented to
     *   the init process.
     * - Because of the Linux / System V semantics of assigning the controlling
     *   tty automagically when a session leader first opens a tty, we will
     *   fork() once more on Linux to get rid of the session leadership role.
     */

    struct sigaction OldSigAct;
    struct sigaction SigAct;
    RT_ZERO(SigAct);
    SigAct.sa_handler = SIG_IGN;
    int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);

    pid_t pid = fork();
    if (pid == -1)
        return RTErrConvertFromErrno(errno);
    if (pid != 0)
        exit(0);

    /*
     * The orphaned child becomes is reparented to the init process.
     * We create a new session for it (setsid), point the standard
     * file descriptors to /dev/null, and change to the root directory.
     */
    pid_t newpgid = setsid();
    int SavedErrno = errno;
    if (rcSigAct != -1)
        sigaction(SIGHUP, &OldSigAct, NULL);
    if (newpgid == -1)
        return RTErrConvertFromErrno(SavedErrno);

    if (!fNoClose)
    {
        /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
        int fd = open("/dev/null", O_RDWR);
        if (fd == -1) /* paranoia */
        {
            close(STDIN_FILENO);
            close(STDOUT_FILENO);
            close(STDERR_FILENO);
            fd = open("/dev/null", O_RDWR);
        }
        if (fd != -1)
        {
            dup2(fd, STDIN_FILENO);
            dup2(fd, STDOUT_FILENO);
            dup2(fd, STDERR_FILENO);
            if (fd > 2)
                close(fd);
        }
    }

    if (!fNoChDir)
        chdir("/");

    /*
     * Change the umask - this is non-standard daemon() behavior.
     */
    umask(027);

# ifdef RT_OS_LINUX
    /*
     * And fork again to lose session leader status (non-standard daemon()
     * behaviour).
     */
    pid = fork();
    if (pid == -1)
        return RTErrConvertFromErrno(errno);
    if (pid != 0)
        exit(0);
# endif /* RT_OS_LINUX */

    if (fRespawn)
    {
        /* We implement re-spawning as a third fork(), with the parent process
         * monitoring the child and re-starting it after a delay if it exits
         * abnormally. */
        unsigned cRespawn = 0;
        for (;;)
        {
            int iStatus, rcWait;

            if (pcRespawn != NULL)
                *pcRespawn = cRespawn;
            pid = fork();
            if (pid == -1)
                return RTErrConvertFromErrno(errno);
            if (pid == 0)
                return VINF_SUCCESS;
            do
                rcWait = waitpid(pid, &iStatus, 0);
            while (rcWait == -1 && errno == EINTR);
            if (rcWait == -1)
                exit(1);
            if (WIFEXITED(iStatus) && WEXITSTATUS(iStatus) == 0)
                exit(0);
            sleep(5);
            ++cRespawn;
        }
    }
    return VINF_SUCCESS;
#endif
}
コード例 #20
0
int main(int argc, char * argv[])
{
  int rc;
  HFILE hfNew;
  HWND hwndNotify;
  char *text;
  HPIPE hpR, hpW;
  ULONG cbRead, cbWritten;
  CHAR achBuf[PIPESIZE]={0};
  CHAR szFailName[CCHMAXPATH];
  HFILE hfSave;
  RESULTCODES ChildRC= {0};
  int a;
  int iBlocks;

  rc=-1;

  if(argc<4) {
    message();
    exit(-1);
  }  

  hwndNotify=atol(argv[1]);

  /* Print the parameters in VIO window */
  printf("argc:%d\n",argc);  
  for(a=0;a<argc;a++)
    {
      printf("%d: %s\n",a,argv[a]);
    }
  printf("\n");
  memset(achBuf, 0, sizeof(achBuf));

  /*  sprintf(achBuf,"%s %s -toc -v",argv[2],argv[3]); */
  sprintf(achBuf,"%s",argv[3]);
  text=strchr(achBuf,0);
  if(!text) {
    WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(4),MPFROMLONG(0));    
  }
  text++;
  sprintf(text,"%s", argv[4]);
  printf("Parameters for size query: %s\n",text);
  text=achBuf; 
  printf("Path is: %s\n",text);

  /**** start  ****/
  
  /* Redirect stdout */ 
  hfSave = -1;// Get new handle
  hfNew = HF_STDOUT;
 
  if(!DosDupHandle(HF_STDOUT, &hfSave)){    /* Saves standard  handle      */
    if(!DosCreatePipe(&hpR, &hpW, PIPESIZE)){ /* Creates pipe            */

      /* If the pipe size is smaller than the output of the child the system() call blocks.
         So create the pipe big enough. */
      
      if(!DosDupHandle(hpW, &hfNew)){           /* Duplicates standard output handle */
  
        /* start CDRecord/2 */
        rc=DosExecPgm(szFailName,sizeof(szFailName),EXEC_ASYNC, text,NULL,&ChildRC, text);
        fprintf(stderr,"DosExecPgm() for dvddao returned: %d\n",rc);
        /*
          rc=system(text);
        */

        DosClose(hpW);                       /* Closes write handle to ensure     */
        /* Notification at child termination */
        DosDupHandle(hfSave, &hfNew);        /* Brings stdout back                */

        /*
         * Read from the pipe and write to the screen
         * as long as there are bytes to read.
         */
          
        do {
          BOOL bNoMedia=FALSE;

          DosRead(hpR, achBuf, sizeof(achBuf), &cbRead);
          DosWrite(HF_STDERR, achBuf, cbRead, &cbWritten);

          /* Uppercase string */
          strupr(achBuf);
          text=strstr(achBuf,"NO MEDIA");
          if(text){
            /* No DVD/CD inserted */
            iBlocks=0;
            //WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(4),MPFROMLONG(0));
            bNoMedia=TRUE;
            break;
          }

          text=strstr(achBuf,"MEDIA SIZE");
          if(text){
            char dummy[200];
            /* We have the size */
            sscanf(text, "%s %s %d", dummy, dummy, &iBlocks);
            break;
          }

        } while(cbRead);          
        printf("Num blocks found %d \n",iBlocks);
        DosClose(hpR);
      }
    }
  }/* if(!DosDupHandle(HF_STDERR, &hfSave)) */      

  printf("Errorcode from dvddao is: %d\n",rc);
  /* Send msg. to the notification window */
  WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(4),MPFROMLONG(iBlocks));
  exit(0);
}
コード例 #21
0
ファイル: Sammy.c プロジェクト: OS2World/UTIL-WPS-WPSam
ULONG ulExecProg (CHAR *szProgName)
   {
   ULONG        ulBootDrive;
   ULONG        ulAppType;
   CHAR         szCmdName[CCHMAXPATH];
   CHAR         szLine[CCHMAXPATH];
   PSZ          pszScanEnv;
   RESULTCODES  rcTermination;
   APIRET       rcFailure = 0;
   PCHAR        pszEnvironment;

/*
 *  Diese Routine versucht eine Shell zu starten.
 */

   pszEnvironment = MakeEnv (pShareInitOS2->pszEnvironment);

   if ( !(rcFailure = ScanEnv(ENV_SAMWORKPLACE, &pszScanEnv, pszEnvironment)) )
      {
      rcFailure = DosQueryAppType(pszScanEnv, &ulAppType);

      if ( !rcFailure )
         if ( ( (ulAppType & 7) == FAPPTYP_NOTSPEC) ||
              ( (ulAppType & 7) == FAPPTYP_WINDOWAPI) )
            rcFailure = DosExecPgm (szLine,           /* Object name buffer */
                                 sizeof(szLine),      /* Length of object name buffer */
                                 EXEC_ASYNCRESULT,    /* Execution flags */
                                 "",                  /* Argument string */
                                 pszEnvironment,       /* Environment */
                                 &rcTermination,      /* Termination codes */
                                 pszScanEnv);         /* Program file name */
         else
            rcFailure = 1;
      }

   if (rcFailure)
      {
      WinAlarm (HWND_DESKTOP, WA_ERROR);
      DebugS (1, "DosExecPgm <1> failed");
      }

   if (rcFailure)
      {
      rcFailure = DosExecPgm (szLine,              /* Object name buffer */
                              sizeof(szLine),      /* Length of object name buffer */
                              EXEC_ASYNCRESULT,    /* Execution flags */
                              "",                  /* Argument string */
                              pszEnvironment,       /* Environment */
                              &rcTermination,      /* Termination codes */
                              szProgName);         /* Program file name */
      }

   if (rcFailure)
      {
      if (!(rcFailure = DosScanEnv (ENV_SAMWORKPLACE, &pszScanEnv)))
         rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "",                  /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           pszScanEnv);         /* Program file name */
      }

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <2> failed");
      DosQuerySysInfo (QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof (ULONG));

      memset (szCmdName, '\0', sizeof(szCmdName));
      szCmdName[0] = (CHAR) (ulBootDrive - 1) + 'A';
      strcpy (szCmdName+1, ":\\OS2\\PMSHELL.EXE");

      rcFailure = DosExecPgm (szLine,           /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "",                  /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           szCmdName);          /* Program file name */
      }

/* Falls Shell nicht gestartet werden konnte, wird cmd.exe aufgerufen */

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <3> failed");
      if (!(rcFailure = DosScanEnv ("COMSPEC", &pszScanEnv)))
         rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "/K",                /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           pszScanEnv);         /* Program file name */
      }

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <4> failed");
      DosQuerySysInfo (QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof (ULONG));

      memset (szCmdName, '\0', sizeof(szCmdName));
      szCmdName[0] = (CHAR) (ulBootDrive - 1) + 'A';
      strcpy (szCmdName+1, ":\\OS2\\CMD.EXE");

      rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                        sizeof(szLine),      /* Length of object name buffer */
                        EXEC_ASYNCRESULT,    /* Execution flags */
                        "/K",                /* Argument string */
                        pszEnvironment,       /* Environment */
                        &rcTermination,      /* Termination codes */
                        szCmdName);          /* Program file name */
      }

   DosFreeMem(pszEnvironment);

   if (rcFailure)
      {
      intSammyRetCode = rcFailure;
      WinPostQueueMsg (hmq, WM_CLOSE, 0L, 0L);
      DebugS (1, "DosExecPgm <5> failed");
      }

   return (rcFailure ? 0 : rcTermination.codeTerminate);
   }
コード例 #22
0
int main(int argc, char * argv[])
{
	int i;
	char cmdLine[CCHMAXPATH*4]={0};
	char * chrPtr;	
    char * chrPtr2;
	HWND hwndNotify;
	char exeName[CCHMAXPATH];//="g:\\projects_working\\audiocpy\\cdrecord.exe";
	char chrError[CCHMAXPATH];
	RESULTCODES resultCodes;
	ULONG rc,ulAction;
    int a;

    char puffer[1024];

    LONG lValue1=0;
    LONG lValue2=0;

    /* Vars for check size */
  int iLeadin;
  int iLeadout;
  int size;
  HFILE hfNew;
  HFILE hfSave;
  HPIPE hpR, hpW;
  ULONG cbRead, cbWritten;
  BOOL bBreak=TRUE;
  char *text,*text2;
  CHAR achBuf[PIPESIZE]={0};
  CHAR szFailName[CCHMAXPATH];
  RESULTCODES ChildRC= {0};
  PID pidChild;
  /*
    argv[0]: progname
    argv[1]: hwnd
    argv[2]: cdrecord path
    argv[3]: dev=x,y,z
   */

    /* Have to check if argc is really 4 */
    if(argc<4) {
      message();
      exit(-1);
    }

    /* Print the parameters in VIO window */
    printf("argc:%d\n",argc);  
    for(a=0;a<argc;a++)
      {
        printf("%d: %s\n",a,argv[a]);
      }
    printf("\n");

    hwndNotify=atol(argv[1]);
    /* Error: no cdrecord options given */
    if(argc<4) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(lValue1),MPFROMLONG(lValue2));
      return;
    }

	/* Get input */
    sprintf(exeName,"%s",argv[2]);// cdrecord/2 path

    for(i=3;i<argc;i++) {
      /* Find 'dev=' in option string */
      chrPtr=strstr(argv[i],"dev=");
      if(chrPtr!=NULL)i=argc;
    }


    /* Build cdrecord/2 cmd-line */
    sprintf(cmdLine,"%s",exeName);
    if((chrPtr=strrchr(cmdLine, 0))==NULL) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
      return;
    }
	chrPtr++;
	sprintf(chrPtr,"%s -msinfo", argv[3]);

	if(DosCreatePipe(&hpR,&hpW,1024)) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
      return;
    }
    if((chrPtr=strrchr(cmdLine, 0))==NULL) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
      return;
    }

    /* Save stdout */
    hfSave=-1;
    if(!DosDupHandle(HF_STDOUT,&hfSave)){/* Saves standard  handle      *//* Saves standard  handle      */
      
      /* Redirect stdout */
      hfNew=HF_STDOUT;
      if(!DosDupHandle(hpW,&hfNew)) {
        
        /* start cdrecord/2 */
        rc=DosExecPgm(chrError,sizeof(chrError),EXEC_ASYNC,cmdLine,0,&resultCodes,exeName);
        fprintf(stderr,"DosExecPgm() for CDRecord/2 returned: %d\n",rc);

        DosClose(hpW);                       /* Closes write handle to ensure     */
        /* Notification at child termination */
        DosDupHandle(hfSave, &hfNew);        /* Brings stdout back                */

        /*
         * Read from the pipe and write to the screen
         * as long as there are bytes to read.
         */

        do {
          /* Retrieve output */
          rc=DosRead(hpR,puffer,sizeof(puffer),&cbRead);
          DosWrite(HF_STDERR, puffer, cbRead, &cbWritten);

          if(cbRead>2) {
            lValue1=atol(puffer);// Previous session start sector
            puffer[1023]=0; //Make sure we have a terminating zero!
            chrPtr=strchr(puffer,',');
            chrPtr++;
            lValue2=atol(chrPtr);
          }
        } while(cbRead);

        DosClose(hpR);
        bBreak=FALSE;
      }/* if(!DosDupHandle(hpW,&hfNew)) */
    }/* if(!DosDupHandle(HF_STDOUT,&hfSave)) */
    /* Get leadin and leadout */

    if(!bBreak) {
      /* Now query size */
      sprintf(achBuf,"%s",argv[2]);/* cdrecord path */
      text=strchr(achBuf,0);
      if(!text) {
        WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));    
      }
      text++;
      sprintf(text,"%s -toc -v", argv[3]);
      printf("Parameters for size query: %s\n",text);
      text=achBuf; 
      printf("Cdrecord path is: %s\n",text);

      /* Redirect stdout */ 
      hfSave = -1;// Get new handle
      hfNew = HF_STDOUT;
      
      if(!DosDupHandle(HF_STDOUT, &hfSave)){    /* Saves standard  handle      */
        if(!DosCreatePipe(&hpR, &hpW, PIPESIZE)){ /* Creates pipe            */
          
          /* If the pipe size is smaller than the output of the child the system() call blocks.
             So create the pipe big enough. */
          
          if(!DosDupHandle(hpW, &hfNew)){           /* Duplicates standard output handle */
            
            /* start CDRecord/2 */
            rc=DosExecPgm(szFailName,sizeof(szFailName),EXEC_ASYNCRESULT, text,NULL,&ChildRC, text);
            fprintf(stderr,"DosExecPgm() for CDRecord/2 returned: %d\n",rc);
            /*
              rc=system(text);
              */
            
            DosClose(hpW);                       /* Closes write handle to ensure     */
            /* Notification at child termination */
            DosDupHandle(hfSave, &hfNew);        /* Brings stdout back                */
            
            /*
             * Read from the pipe and write to the screen
             * as long as there are bytes to read.
             */
            
            do {
              DosRead(hpR, achBuf, sizeof(achBuf), &cbRead);
              DosWrite(HF_STDERR, achBuf, cbRead, &cbWritten);
              
              text=strstr(achBuf,"ATIP");
              
              if(text){
                /* Check if we have a lead in section */
                text2=strstr(text,"in:");
                if(text2) {
                  /* Yes, we have a lead in. Seems to be a blank disk. Find lead out now */
                  iLeadin=0;
                  text2++;
                  text=strstr(text2,"ATIP");/* Second ATIP shows lead out of blank disk */
                  if(text)
                    sscanf(text,"%[^:]: %ld",szFailName,&iLeadout);
                }/* if(text2) */
                else {
                  /* No lead in section. It seems to be a disk with some tracks already written */
                  sscanf(text,"%[^:]: %ld",szFailName,&iLeadout); /* ATIP shows disk lead out */
                  text2=strstr(text,"lout");
                  if(!text2){/* Error */
                    iLeadin=iLeadout;/* Set disk size to zero as error */
                    break;
                  }
                  /* Lead out of track is lead in of next track */
                  sscanf(text2,"%[^:]: %ld",szFailName,&iLeadin);
                }
              }
            } while(cbRead);          
            printf("Leadin is  %d \n",iLeadin); /* We use stdout because stderr is redirected */
            printf("Leadout is  %d \n",iLeadout);
            DosClose(hpR);
          }
        }
      }/* if(!DosDupHandle(HF_STDERR, &hfSave)) */      

      DosWaitChild(DCWA_PROCESS, DCWW_WAIT,&ChildRC, &pidChild, ChildRC.codeTerminate);
      if(ChildRC.codeResult!=0) {
        WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
        exit(0);
      }

      /* Calculate free space */
      size=iLeadout-iLeadin;
      if(iLeadin) {
        /* Because iLeadin isn't zero, the disk seems to be a disk with already written session.
           11400 sectors must be substracted from the size as lead in for the next session */
        if(size<11400)
          size=0;
        else
          size-=11400;
      }
    }
    printf("1. sector: %d\n2. sector: %d\n", lValue1, lValue2);

    /* The following kombinations of leadin, out, 1. sector and 2. sector are possible:
       Open CD with previous session:  xxx,  xxx,  ???,  xxx
       Empty CD:                       0  ,  xxx,  0  ,  0
       Closed CD:                      0  ,  0  ,  0  ,  0 (???)
       Closed CD:                      xxx,  xxxx,  0  ,  0
       No CD:                          0  ,  0  ,  0  ,  0
       */
    /* Full or no CD -> Error */
    if(!lValue1 && !lValue2 && !iLeadin && !iLeadout) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
      exit(0);
    }
    if(!lValue1 && !lValue2 && iLeadin && iLeadout) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(0),MPFROMLONG(0));
      exit(0);
    }

    /* Empty CD. Mark it by sending 1 for the sectors */
    if(!lValue1 && !lValue2  && iLeadout) {
      WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(1),MPFROMLONG(1));
      exit(0);
    }

	/* Send the two values to our notification window */
    WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(lValue1),MPFROMLONG(lValue2));
    exit(0);
}
コード例 #23
0
ファイル: hbproces.c プロジェクト: mikomc/harbour-core
HB_FHANDLE hb_fsProcessOpen( const char * pszFileName,
                             HB_FHANDLE * phStdin, HB_FHANDLE * phStdout,
                             HB_FHANDLE * phStderr,
                             HB_BOOL fDetach, HB_ULONG * pulPID )
{
   HB_FHANDLE hPipeIn [ 2 ] = { FS_ERROR, FS_ERROR },
              hPipeOut[ 2 ] = { FS_ERROR, FS_ERROR },
              hPipeErr[ 2 ] = { FS_ERROR, FS_ERROR };
   HB_FHANDLE hResult = FS_ERROR;
   HB_ERRCODE errCode;
   HB_BOOL fError = HB_FALSE;

   HB_TRACE( HB_TR_DEBUG, ( "hb_fsProcessOpen(%s, %p, %p, %p, %d, %p)", pszFileName, phStdin, phStdout, phStderr, fDetach, pulPID ) );

   if( phStdin != NULL )
      fError = ! hb_fsPipeCreate( hPipeIn );
   if( ! fError && phStdout != NULL )
      fError = ! hb_fsPipeCreate( hPipeOut );
   if( ! fError && phStderr != NULL )
   {
      if( phStdout == phStderr )
      {
         hPipeErr[ 0 ] = hPipeOut[ 0 ];
         hPipeErr[ 1 ] = hPipeOut[ 1 ];
      }
      else
         fError = ! hb_fsPipeCreate( hPipeErr );
   }

   if( ! fError )
   {
#if defined( HB_OS_WIN )

      PROCESS_INFORMATION pi;
      STARTUPINFO si;
      DWORD dwFlags = 0;
      LPTSTR lpCommand = HB_CHARDUP( pszFileName );

#  if ! defined( HB_OS_WIN_CE )
      if( phStdin != NULL )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 1 ] ), HANDLE_FLAG_INHERIT, 0 );
      if( phStdout != NULL )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 0 ] ), HANDLE_FLAG_INHERIT, 0 );
      if( phStderr != NULL && phStdout != phStderr )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 0 ] ), HANDLE_FLAG_INHERIT, 0 );
#  endif

      memset( &pi, 0, sizeof( pi ) );
      memset( &si, 0, sizeof( si ) );
      si.cb = sizeof( si );
#  ifdef STARTF_USESTDHANDLES
      si.dwFlags = STARTF_USESTDHANDLES;
#  endif
      if( fDetach )
      {
#  ifdef STARTF_USESHOWWINDOW
         si.dwFlags |= STARTF_USESHOWWINDOW;
#  endif
         si.wShowWindow = SW_HIDE;
         si.hStdInput  = ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 0 ] );
         si.hStdOutput = ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 1 ] );
         si.hStdError  = ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 1 ] );
#  ifdef DETACHED_PROCESS
         dwFlags |= DETACHED_PROCESS;
#  endif
      }
      else
      {
         si.hStdInput  = phStdin  ? ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 0 ] ) : GetStdHandle( STD_INPUT_HANDLE );
         si.hStdOutput = phStdout ? ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 1 ] ) : GetStdHandle( STD_OUTPUT_HANDLE );
         si.hStdError  = phStderr ? ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 1 ] ) : GetStdHandle( STD_ERROR_HANDLE );
      }
      fError = ! CreateProcess( NULL,           /* lpAppName */
                                lpCommand,
                                NULL,           /* lpProcessAttr */
                                NULL,           /* lpThreadAttr */
                                TRUE,           /* bInheritHandles */
                                dwFlags,        /* dwCreationFlags */
                                NULL,           /* lpEnvironment */
                                NULL,           /* lpCurrentDirectory */
                                &si,
                                &pi );
      hb_fsSetIOError( ! fError, 0 );
      hb_xfree( lpCommand );
      if( ! fError )
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pi.dwProcessId;
         CloseHandle( pi.hThread );
         hResult = ( HB_FHANDLE ) pi.hProcess;
      }

#elif defined( HB_OS_OS2 )

      HFILE hNull = ( HFILE ) FS_ERROR;
      ULONG ulState = 0;
      APIRET ret = NO_ERROR;
      PID pid = ( PID ) -1;
      PHB_GT pGT;

      if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
      {
         HB_FHANDLE hFile;

         ret = hb_fsOS2DosOpen( "NUL:", &hFile, &ulState, 0,
                                FILE_NORMAL, OPEN_ACCESS_READWRITE,
                                OPEN_ACTION_OPEN_IF_EXISTS );
         if( ret == NO_ERROR )
            hNull = ( HFILE ) hFile;
      }

      if( ret == NO_ERROR && phStdin != NULL )
      {
         ret = DosQueryFHState( hPipeIn[ 1 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeIn[ 1 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }
      if( ret == NO_ERROR && phStdout != NULL )
      {
         ret = DosQueryFHState( hPipeOut[ 0 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeOut[ 0 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }
      if( ret == NO_ERROR && phStderr != NULL && phStdout != phStderr )
      {
         ret = DosQueryFHState( hPipeErr[ 0 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeErr[ 0 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }

      if( ret == NO_ERROR && ( pGT = hb_gt_Base() ) != NULL )
      {
         ULONG ulStateIn, ulStateOut, ulStateErr;
         HFILE hStdIn, hStdErr, hStdOut, hDup;

         ulStateIn = ulStateOut = ulStateErr = OPEN_FLAGS_NOINHERIT;
         hStdIn  = hStdErr = hStdOut = ( HFILE ) FS_ERROR;

         if( ret == NO_ERROR && ( phStdin != NULL || fDetach ) )
         {
            hDup = 0;
            ret = DosDupHandle( hDup, &hStdIn );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdIn, &ulStateIn );
               if( ret == NO_ERROR && ( ulStateIn & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdIn, ( ulStateIn & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStdin != NULL ? ( HFILE ) hPipeIn[ 0 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR && ( phStdout != NULL || fDetach ) )
         {
            hDup = 1;
            ret = DosDupHandle( hDup, &hStdOut );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdOut, &ulStateOut );
               if( ret == NO_ERROR && ( ulStateOut & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdOut, ( ulStateOut & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStdout != NULL ? ( HFILE ) hPipeOut[ 1 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR && ( phStderr != NULL || fDetach ) )
         {
            hDup = 2;
            ret = DosDupHandle( hDup, &hStdErr );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdErr, &ulStateErr );
               if( ret == NO_ERROR && ( ulStateErr & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdErr, ( ulStateErr & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStderr != NULL ? ( HFILE ) hPipeErr[ 1 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR )
         {
            char * pArgs = hb_buildArgsOS2( pszFileName, &ret );
            char uchLoadError[ CCHMAXPATH ] = { 0 };
            RESULTCODES ChildRC = { 0, 0 };

            if( pArgs )
            {
               ret = DosExecPgm( uchLoadError, sizeof( uchLoadError ),
                                 fDetach ? EXEC_BACKGROUND : EXEC_ASYNCRESULT,
                                 ( PCSZ ) pArgs, NULL /* env */,
                                 &ChildRC,
                                 ( PCSZ ) pArgs );
               if( ret == NO_ERROR )
                  pid = ChildRC.codeTerminate;
               hb_freeArgsOS2( pArgs );
            }
         }

         if( hNull != ( HFILE ) FS_ERROR )
            DosClose( hNull );

         if( hStdIn != ( HFILE ) FS_ERROR )
         {
            hDup = 0;
            DosDupHandle( hStdIn, &hDup );
            DosClose( hStdIn );
            if( ( ulStateIn & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateIn & 0xFF00 );
         }
         if( hStdOut != ( HFILE ) FS_ERROR )
         {
            hDup = 1;
            DosDupHandle( hStdOut, &hDup );
            DosClose( hStdOut );
            if( ( ulStateOut & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateOut & 0xFF00 );
         }
         if( hStdErr != ( HFILE ) FS_ERROR )
         {
            hDup = 2;
            DosDupHandle( hStdErr, &hDup );
            DosClose( hStdErr );
            if( ( ulStateErr & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateErr & 0xFF00 );
         }

         hb_gt_BaseFree( pGT );
      }
      else
      {
         if( hNull != ( HFILE ) FS_ERROR )
            DosClose( hNull );
         if( ret == NO_ERROR )
            ret = ( APIRET ) FS_ERROR;
      }

      fError = ret != NO_ERROR;
      if( ! fError )
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }

      hb_fsSetError( ( HB_ERRCODE ) ret );

#elif defined( HB_OS_UNIX ) && \
      ! defined( HB_OS_VXWORKS ) && ! defined( HB_OS_SYMBIAN )

      char ** argv = hb_buildArgs( pszFileName );
      pid_t pid = fork();

      if( pid == -1 )
         fError = HB_TRUE;
      else if( pid != 0 )    /* parent process */
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }
      else                    /* child process */
      {
         if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
         {
            HB_FHANDLE hNull = open( "/dev/null", O_RDWR );

            if( ! phStdin )
               dup2( hNull, 0 );
            if( ! phStdout )
               dup2( hNull, 1 );
            if( ! phStderr )
               dup2( hNull, 2 );

            if( hNull != FS_ERROR )
               hb_fsClose( hNull );
         }

         if( phStdin != NULL )
         {
            dup2( hPipeIn[ 0 ], 0 );
            hb_fsClose( hPipeIn[ 1 ] );
         }
         if( phStdout != NULL )
         {
            dup2( hPipeOut[ 1 ], 1 );
            hb_fsClose( hPipeOut[ 0 ] );
         }
         if( phStderr != NULL )
         {
            dup2( hPipeErr[ 1 ], 2 );
            if( phStdout != phStderr )
               hb_fsClose( hPipeErr[ 0 ] );
         }

         /* close all non std* handles */
         {
            int iMaxFD, i;
            iMaxFD = sysconf( _SC_OPEN_MAX );
            if( iMaxFD < 3 )
               iMaxFD = 1024;
            for( i = 3; i < iMaxFD; ++i )
               hb_fsClose( i );
         }

         /* reset extended process attributes */
         if( setuid( getuid() ) == -1 ) {}
         if( setgid( getgid() ) == -1 ) {}

         /* execute command */
         {
#  if defined( __WATCOMC__ )
            execvp( argv[ 0 ], ( const char ** ) argv );
#  else
            execvp( argv[ 0 ], argv );
#  endif
            exit( -1 );
         }
      }
      hb_fsSetIOError( ! fError, 0 );

      hb_freeArgs( argv );

#elif defined( HB_OS_OS2 ) || defined( HB_OS_WIN )

      int hStdIn, hStdOut, hStdErr;
      char ** argv;
      int pid;

      hStdIn  = dup( 0 );
      hStdOut = dup( 1 );
      hStdErr = dup( 2 );

      if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
      {
         HB_FHANDLE hNull = open( "NUL:", O_RDWR );

         if( ! phStdin )
            dup2( hNull, 0 );
         if( ! phStdout )
            dup2( hNull, 1 );
         if( ! phStderr )
            dup2( hNull, 2 );

         if( hNull != FS_ERROR )
            close( hNull );
      }

      if( phStdin != NULL )
         dup2( hPipeIn[ 0 ], 0 );
      if( phStdout != NULL )
         dup2( hPipeOut[ 1 ], 1 );
      if( phStderr != NULL )
         dup2( hPipeErr[ 1 ], 2 );

      argv = hb_buildArgs( pszFileName );

#if defined( _MSC_VER ) || defined( __LCC__ ) || \
    defined( __XCC__ ) || defined( __POCC__ )
      pid = _spawnvp( _P_NOWAIT, argv[ 0 ], argv );
#elif defined( __MINGW32__ ) || defined( __WATCOMC__ )
      pid = spawnvp( P_NOWAIT, argv[ 0 ], ( const char * const * ) argv );
#else
      pid = spawnvp( P_NOWAIT, argv[ 0 ], ( char * const * ) argv );
#endif
      hb_freeArgs( argv );

      dup2( hStdIn,  0 );
      close( hStdIn );

      dup2( hStdOut, 1 );
      close( hStdOut );

      dup2( hStdErr, 2 );
      close( hStdErr );

      if( pid < 0 )
         fError = HB_TRUE;
      else if( pid != 0 )    /* parent process */
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }

      hb_fsSetIOError( ! fError, 0 );

#else
      int iTODO; /* TODO: for given platform */

      HB_SYMBOL_UNUSED( pszFileName );
      HB_SYMBOL_UNUSED( fDetach );
      HB_SYMBOL_UNUSED( pulPID );

      hb_fsSetError( ( HB_ERRCODE ) FS_ERROR );
#endif
   }

   errCode = hb_fsError();

   if( hPipeIn[ 0 ] != FS_ERROR )
      hb_fsClose( hPipeIn[ 0 ] );
   if( hPipeIn[ 1 ] != FS_ERROR )
      hb_fsClose( hPipeIn[ 1 ] );
   if( hPipeOut[ 0 ] != FS_ERROR )
      hb_fsClose( hPipeOut[ 0 ] );
   if( hPipeOut[ 1 ] != FS_ERROR )
      hb_fsClose( hPipeOut[ 1 ] );
   if( phStdout != phStderr )
   {
      if( hPipeErr[ 0 ] != FS_ERROR )
         hb_fsClose( hPipeErr[ 0 ] );
      if( hPipeErr[ 1 ] != FS_ERROR )
         hb_fsClose( hPipeErr[ 1 ] );
   }

   hb_fsSetError( errCode );

   return hResult;
}
コード例 #24
0
ファイル: con_os2.cpp プロジェクト: AaronDP/efte_adbshell
static int CreatePipeChild(PID& pid, HPIPE& hfPipe, char *Command) {
  static int PCount = 0;
  char  szPipe[32];
  char  FailBuf[256];
  char *Args;
  int   arglen = 0;
  char *Prog;
  RESULTCODES rc_code;
  ULONG ulAction;

  // ULONG ulNew;
  HPIPE hfChildPipe;
  HFILE hfNewStdOut = (HFILE)-1, hfNewStdErr = (HFILE)-1;
  HFILE hfStdOut    = 1, hfStdErr = 2;
  int   rc;

  sprintf(szPipe, "\\PIPE\\eFTE%d\\CHILD%d", getpid(), PCount);
  PCount++;

  rc = DosCreateNPipe(szPipe, &hfPipe,
                      NP_NOINHERIT | NP_ACCESS_INBOUND,
                      NP_NOWAIT | NP_TYPE_BYTE | NP_READMODE_BYTE | 1,
                      0, 4096, 0);

  if (rc != 0) return -1;

  rc = DosConnectNPipe(hfPipe);

  if ((rc != 0) && (rc != ERROR_PIPE_NOT_CONNECTED)) {
    DosClose(hfPipe);
    return -1;
  }

  rc = DosSetNPHState(hfPipe, NP_WAIT | NP_READMODE_BYTE);

  if (rc != 0) {
    DosClose(hfPipe);
    return -1;
  }

  rc = DosOpen(szPipe, &hfChildPipe, &ulAction, 0,
               FILE_NORMAL,
               OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW,
               OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE,
               NULL);

  if (rc != 0) {
    DosClose(hfPipe);
    return -1;
  }

  // Duplicate handles
  DosDupHandle(hfStdOut, &hfNewStdOut);
  DosDupHandle(hfStdErr, &hfNewStdErr);

  // Close existing handles for current process
  DosClose(hfStdOut);
  DosClose(hfStdErr);

  // Redirect existing handles to new file
  DosDupHandle(hfChildPipe, &hfStdOut);
  DosDupHandle(hfChildPipe, &hfStdErr);

  // Let started program inherit handles from parent

  Prog = getenv("COMSPEC");

  Args = (char *)malloc(strlen(Prog) + 1
                        + 3 + strlen(Command) + 1
                        + 1);

  if (Args == NULL) {
    DosClose(hfPipe);
    return -1;
  }

  strcpy(Args,          Prog);
  arglen = strlen(Args) + 1;
  strcpy(Args + arglen, "/c ");
  arglen += 3;
  strcpy(Args + arglen, Command);
  arglen      += strlen(Command) + 1;
  Args[arglen] = '\0';

  rc = DosExecPgm(FailBuf, sizeof(FailBuf),
                  EXEC_ASYNCRESULT, // | EXEC_BACKGROUND,
                  Args,
                  0,
                  &rc_code,
                  Prog);

  free(Args);

  // Get back original handles
    DosDupHandle(hfNewStdOut, &hfStdOut);
    DosDupHandle(hfNewStdErr, &hfStdErr);

  // Close the duplicated handles - no longer needed
    DosClose(hfNewStdOut);
    DosClose(hfNewStdErr);

    DosClose(hfChildPipe); // pipe one way, close out write end

  if (rc != 0) {
    DosClose(hfPipe);
    return -1;
  }

  pid = rc_code.codeTerminate; // get pid when successful

  return 0;
}
コード例 #25
0
int main(int argc, char * argv[])
{
	int i;
	char cmdLine[CCHMAXPATH*4]={0};
	char cmdLineBuff[CCHMAXPATH*4];
	char * chrPtr;
	HWND hwndNotify;
	char exeName[CCHMAXPATH];//"g:\\projects_working\\audiocpy\\show.exe";
	char chrError[CCHMAXPATH];
	char logName[CCHMAXPATH];
	RESULTCODES resultCodes;
	ULONG rc,ulAction;
	HFILE hf,hfNew;

    if(argc<3) {
      message();
      exit(-1);
    }
	
    hwndNotify=atol(argv[1]);

	sprintf(exeName,"%s",argv[2]);
	sprintf(logName,"%s\\Logfiles\\write.log",argv[3]);
	
	sprintf(cmdLine,exeName);
	chrPtr=strrchr(cmdLine,0);
	chrPtr++;

	/* Build parameters */
    for(i=4;i<argc;i++) {
      sprintf(cmdLineBuff,"%s",chrPtr);
      sprintf(chrPtr,"%s %s",cmdLineBuff,argv[i]);
    }
    /* Replace ' with " */
    changeChar(chrPtr,'\'','\"');

    /* Replace ^ with space */
    changeChar(chrPtr,'^',' ');

	printf("HWND: %ld",hwndNotify);
	printf("\n");	
	printf("cdrecord-executable: %s",exeName);
	printf("\n");
	printf("Logname: %s\n",logName);
	printf("cdrecord parameter: %s",chrPtr);
	printf("\n");

	/* Redirect stderr */
    rc=DosOpen(logName,&hf,&ulAction,0,FILE_NORMAL,OPEN_ACTION_CREATE_IF_NEW|OPEN_ACTION_OPEN_IF_EXISTS,
               OPEN_ACCESS_WRITEONLY|OPEN_SHARE_DENYWRITE,0);
	if(!rc) {
		DosSetFilePtr(hf,0,FILE_END,&ulAction);
		hfNew=2;
		DosDupHandle(hf,&hfNew);
		
		sprintf(logName,"---------------------------------------------------------------------\n");
		write(2,logName,strlen(logName));

		sprintf(logName,"\n");
		write(2,logName,strlen(logName));	
        
		/*	time(&ltime);		
		sprintf(logName,"%s",ctime(&ltime));
		write(2,logName,strlen(logName));	
		sprintf(logName,"\n");
		write(2,logName,strlen(logName));	*/
    
		sprintf(logName,"Starting to write using %s\n",exeName);
		write(2,logName,strlen(logName));
		
		sprintf(logName,"with the following parameters: %s\n",chrPtr);
		write(2,logName,strlen(logName));
	}
	
	DosExecPgm(chrError,sizeof(chrError),EXEC_SYNC,cmdLine,0,&resultCodes,exeName);
	sprintf(logName,"Return code is: %ld\n ",resultCodes.codeResult);
	write(2,logName,strlen(logName));

    DosClose(hf);
    WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_WRITEONLY),MPFROMLONG(resultCodes.codeResult));
    return 0;
}
コード例 #26
0
 int main(VOID) {

 UCHAR       uchLoadError[CCHMAXPATH] = {0}; /* Error info from DosExecPgm */

 RESULTCODES ChildRC           = {0};       /* Results from child process  */

 PID         pidChild          = 0;         /* pid for child process       */

 APIRET      rc                = NO_ERROR;  /* Return code                 */

 UCHAR       uchEnvString[14]  = "ANYTHING=HERE\0";  /* Environment string */

 UCHAR       uchArgString[14]  = "CHKDSK\0 C: \0";   /* Argument string    */



       /* The argument string consists of the following:

             - the name of the program (followed by a NULL)

             - any parameters supplied to the program (followed by 2 NULLs)

          Only 1 NULL is explicitly specified at the end of this string.

          ASCIIZ strings end with a NULL already, giving us 2 NULLs.       */



   rc = DosExecPgm(uchLoadError,           /* Object name buffer           */

                   sizeof(uchLoadError),   /* Length of object name buffer */

                   EXEC_ASYNCRESULT,       /* Asynchronous/Trace flags     */

                   uchArgString,           /* Argument string              */

                   uchEnvString,           /* Environment string           */

                   &ChildRC,               /* Returns pid of process on an

                                              asynchronous request         */

                   "CHKDSK.COM");          /* Program file name            */



   if (rc != NO_ERROR) {

      printf("DosExecPgm error: return code = %u\n",rc);

      return 1;

   }



   rc = DosWaitChild(DCWA_PROCESS,    /* Look at only the process specified */

                     DCWW_WAIT,       /* Wait until a child terminates      */

                     &ChildRC,        /* Termination codes returned         */

                     &pidChild,       /* pid of terminating process         */

                     ChildRC.codeTerminate);   /* Process (pid) to look at  */



   if (rc != NO_ERROR) {

      printf("DosWaitChild error: return code = %u\n",rc);

      return 1;

   } else {

      printf("Child complete.  Termination Code: %u  Return Code: %u\n",

              ChildRC.codeTerminate, ChildRC.codeResult);

   }

   return NO_ERROR;

  }
コード例 #27
0
VOID main( VOID )
{
 // ********************************************************** //

 // Можно создать приложение, *.dll или *.obj.
 CHAR Target[] = "/Ge+ /Ss+";    // Приложение.
 // CHAR Target[] = "/C /Ss+";   // Object.
 // CHAR Target[] = "/Ge- /Ss+"; // Library.

 // Процессор - Pentium.
 CHAR Processor[] = "/G5 /Gf+ /Gi+";

 // Оптимизация - по скорости.
 CHAR Optimization[] = "/Gs+ /O+ /Oi+";

 // Размер стека - как и у всех потоков.
 CHAR Stack_size[] = "/B\"/ST:32768\"";

 // Имена файлов.
 CHAR CPP_Name[] = "Nice-os2.cpp";
 CHAR DEF_Name[] = "Nice-os2.def";
 CHAR LIB_Name[] = "..\\Shared\\DosCalls\\Doscalls.lib";

 CHAR RC_Name[] =  "Resources\\Resources.rc";
 CHAR RES_Name[] = "Resources\\Resources.res";

 CHAR OBJ_Name[] = "Nice-os2.obj";
 CHAR TGT_Name[] = "Nice-os2.exe ";

 // ********************************************************** //

 // Задаем параметры.
 CHAR Compiler[] = "Icc.exe"; CHAR Parameters[ 255 ] = "";
 strcpy( Parameters, Compiler );     strcat( Parameters, "|" );
 strcat( Parameters, Target );       strcat( Parameters, " " );
 strcat( Parameters, CPP_Name );     strcat( Parameters, " " );
 strcat( Parameters, DEF_Name );     strcat( Parameters, " " );
 strcat( Parameters, LIB_Name );     strcat( Parameters, " " );
 strcat( Parameters, Processor );    strcat( Parameters, " " );
 strcat( Parameters, Optimization ); strcat( Parameters, " " );
 strcat( Parameters, Stack_size );
 strchg( Parameters, '|', 0x00 );

 // Удаляем файлы, которые требуется получить.
 DosForceDelete( TGT_Name );

 // Вызываем IBM VA C++.
 CHAR Error_string[ 1 ]; RESULTCODES Return_codes;
 DosResetBuffer( -1 ); DosExecPgm( Error_string, sizeof( Error_string ), EXEC_SYNC, Parameters, NULL, &Return_codes, Compiler );

 // Задаем параметры для Resource Compiler.
 // RC.exe - 16-разрядное приложение, и его надо вызвать как "Cmd /C RC.exe".
 CHAR RC_starter[] = "Cmd.exe"; Parameters[ 0 ] = 0;
 strcpy( Parameters, RC_starter );   strcat( Parameters, "|" );
 strcat( Parameters, "/C RC.exe" );  strcat( Parameters, " " );
 strcat( Parameters, RC_Name );      strcat( Parameters, " " );
 strcat( Parameters, TGT_Name );
 strchg( Parameters, '|', 0x00 );

 // Вызываем Resource Compiler.
 DosResetBuffer( -1 ); DosExecPgm( Error_string, sizeof( Error_string ), EXEC_SYNC, Parameters, NULL, &Return_codes, RC_starter );

 // Удаляем временные файлы.
 DosForceDelete( OBJ_Name ); DosForceDelete( RES_Name );

 // Звук.
 WinAlarm( HWND_DESKTOP, WA_NOTE );

 // Выход.
 return;
}
コード例 #28
0
ファイル: Console.c プロジェクト: OS2World/UTIL-WPS-Console
void doSameSession()
{
 char *arg;
 RESULTCODES rc;
 int i,j;

 if (progtitle)
  SetConsoleTitle(progtitle);

 if (fForegroundConsole)
  SelectConsole();

 if (fConsoleSize)
  SetConsoleSize(Console.W, Console.H, colSAME);

 if (fFontSet)
 {
  RECTL r;
  LockConsoleUpdate();
  SetConsoleFontSize(Font.H, Font.W);
  if (fResizeWindowToMax && !fExplicitSize)
   SetMaxConsoleSize();

  // Workaround: NPS WPS does not redraw window shadow when window grows :-(
  GetPixelConsoleSize((int *)&r.xLeft, (int *)&r.yBottom, (int *)&r.xRight, (int *)&r.yTop);
  r.xRight += r.xLeft + 8; r.yTop += r.yBottom + 8;
  r.xLeft -= 8; r.yBottom -= 8;
  WinInvalidateRect(HWND_DESKTOP, &r, FALSE);

  UnlockConsoleUpdate();
 } else
 if (fResizeWindowToMax && !fExplicitSize)
  SetMaxConsoleSize();

 if (fSetBorder)
  SetConsoleBorderSize(Border.W, Border.H);
 if (fSetFlash)
  FlashConsole(fFlashWindow);

 if (fMinimizeConsole)
  MinimizeConsole();
 else if (fMaximizeConsole)
  MaximizeConsole();

 if (GetWindowHWND())
 {
  if ((fExplicitPos || fExplicitSize))
   SetPixelConsoleSize(ConsolePos.X, ConsolePos.Y, ConsolePos.W, ConsolePos.H,
    (fExplicitPos ? SWP_MOVE : 0) | (fExplicitSize ? SWP_SIZE : 0));
  else if (fMaximizeConsole)
   SetPixelConsoleSize(ConsolePos.X, ConsolePos.Y, 0, 0, SWP_MOVE);
 }

 if (fHideConsole)
  ShowConsole(FALSE);
 else if (fShowConsole)
  ShowConsole(TRUE);

 if (fRestoreConsole)
  RestoreConsole();

 if (!progname) return;
 if (!progname[0]) progname = getenv("COMSPEC");
 if (progname) i = strlen(progname); else i = 0;
 j = i; i++;
 if (progargs) i+= strlen(progargs);
 arg = malloc(i);

 if (progname) strcpy(arg, progname); else arg[0] = 0;
 strcat(arg, "*");
 if (progargs) strcat(arg, progargs);
 arg[j] = 0;

 ReleaseINI();
 if (DosExecPgm(NULL, 0, EXEC_SYNC, arg, NULL, &rc, progname))
 {
  SetColor(colLRED, colSAME);
  printf("Error running command %s\n", progname);
  if (_isterm(1)) getch();
  return;
 }
}
コード例 #29
0
int main(int argc, char * argv[])
{
  char achBuf[PIPESIZE];
  char achBuf2[PIPESIZE];
  char szFailName[CCHMAXPATH];

  int rc;
  HFILE hfNew;
  HFILE hfSave;
  HPIPE hpR, hpW;

  HFILE hfNew2;
  HFILE hfSaveOutput;
  HPIPE hpR2, hpW2;


  ULONG cbRead, cbRead2, cbWritten;
  HWND hwndNotify;
  char *text;
  char *mem;
  char *ptrLocalMem;
  int a;


  UCHAR LoadError[CCHMAXPATH]= {0};
  RESULTCODES ChildRC= {0};
  PID pidChild;
  FILE* fh;
  char* pipePtr;
  char* fifoPtr;
  FILE * pipe;
  LONG writtenB=0;
  LONG delta=0;
  LONG lNoFix=0;
  int iFifo=0;
  BOOL bPriority=FALSE;
  FILE *file;

  rc=-1;

  /*
    argv[0]=progname
    argv[1]=HWND 
    argv[2]=cdrecord path
    argv[3]=installation dir
    argv[4]=Parameter filename
    argv[5]=logfilename
   */

  for(a=0;a<argc;a++)
    printf("%d:  %s\n", a, argv[a]);
    
  if(argc<6) {
    message();
    exit(-1);
  }  

  hwndNotify=atol(argv[1]);

  if((ptrLocalMem=malloc(SHAREDMEM_SIZE))==NULL){
    WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_PRINTSIZE),MPFROMLONG(0));
    exit(255);
  }
  /* Open file with parameters */
  if((file=fopen(argv[4],"rb"))==NULL){
    WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_PRINTSIZE),MPFROMLONG(0));
    exit(255);
  }
  
  /* Copy command line to local memory */
  fread(ptrLocalMem, sizeof(char), SHAREDMEM_SIZE, file);
  fclose(file);

  /* Open log file */
  snprintf(LoadError, sizeof(LoadError), "%s\\%s",argv[3], argv[5]);
  fh=fopen(LoadError,"a");

  /* Get cmd line */
  text=ptrLocalMem;
  
  /* find pipe char */
  pipePtr=strchr(text,'|');
  
  mem=strstr(text,"-print-size");
  for(a=0;a<strlen("-print-size");a++) {
    *mem=' ';
    mem++;
  }
  
  if(fh) {
    fputs("\n---------------------------------------------------------------\n",fh);
    fputs("Starting the helper \"",fh);
    fputs(argv[0],fh);
    fputs("\" with the following parameters:\n",fh);
    fputs(text,fh);
    fputs("\n\n",fh);
  }
  
  /* Find end of mkisofs path */
  mem=strchr(text,'"');
  *mem=0;
  
  if(pipePtr) {
    *pipePtr=0;
    pipePtr++;
    *pipePtr=0;
    pipePtr++;
  }
  /* pipePtr points to begin of cdrecord path */
  if(strstr(pipePtr,"-nofix"))
    lNoFix=1;
  
  /* FIFO size. Needing it to know when FIFO is filled. We raise the priority of the mkisofs
     process then.
     */
  if((fifoPtr=strstr(pipePtr,"fs="))!=NULLHANDLE) {
    fifoPtr+=3;
    iFifo=atoi(fifoPtr);
    iFifo*=1024*1024;
  }        
  
#ifdef DEBUG    
  //      DosFreeMem(pvSharedMem);
  free(ptrLocalMem);
  WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_ONTHEFLY),MPFROMSHORT(rc));
  exit(0);
#endif

  fflush(stdout);
  fflush(stderr);
  
  hfSaveOutput = -1;// Get new handle
  hfNew2 = HF_STDOUT;
  
  if(!DosDupHandle(HF_STDOUT, &hfSaveOutput)) {
        if(!DosCreatePipe(&hpR2, &hpW2, PIPESIZE)) {
          if(!DosDupHandle(hpW2, &hfNew2)){/* Duplicates standard out handle */

            /* Start mkisofs */
            rc=DosExecPgm(LoadError,sizeof(LoadError),EXEC_ASYNCRESULT, text,NULL,&ChildRC,text);
            sprintf(achBuf,"DosExecPgm() for mkisofs returned: %d\n",rc);
            if(fh)
              fputs(achBuf,fh);
            
            DosClose(hpW2);                       /* Closes write handle to ensure     */
            /* Notification at child termination */
            
            DosDupHandle(hfSaveOutput, &hfNew2);        /* Brings stdout back                */   
            /* pipePtr points to begin of cdrecord path */
            pipe=popen(pipePtr,"wb");

            /*
             * Read from the pipe and write to the screen
             * as long as there are bytes to read.
             */          
            do {
              /* Read from mkisofs */
              DosRead(hpR2, achBuf2, sizeof(achBuf2), &cbRead2);

              /* Read output of cdrecord */
              //DosRead(hpR, achBuf, sizeof(achBuf), &cbRead);
              //DosWrite(HF_STDERR, achBuf, cbRead, &cbWritten);
              //   sscanf(achBuf,"%[^=]= %ld",szFailName,&size);       

              /* Write output of mkisofs */
              if(cbRead2)
                fwrite(achBuf2,sizeof(BYTE),cbRead2,pipe);
              
              delta+=cbRead2;
              writtenB+=cbRead2;
              if(delta>=PIPESIZE*200) {
                delta=0;
                WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_MBWRITTEN),MPFROMLONG(writtenB));
              }
              if(writtenB>=iFifo && !bPriority) {
                fputs("FIFO filled, increasing priority of mkisofs process.\n", fh);
                bPriority=TRUE;
                rc=DosSetPriority(PRTYS_PROCESS,PRTYC_TIMECRITICAL,30,ChildRC.codeTerminate);
                sprintf(LoadError,"DosSetPriority() returned: %d (should be 0)\n", rc);
                fputs(LoadError,fh);
                fputs("Increasing priority of the on-the-fly helper process.\n",fh);
                // rc=DosSetPriority(PRTYS_PROCESS,PRTYC_TIMECRITICAL,20,0);
                /* Is this kind of priority setting ok? */
                rc=DosSetPriority(PRTYS_PROCESS,PRTYC_TIMECRITICAL,30,0);
                sprintf(LoadError,"DosSetPriority() returned: %d (should be 0)\n", rc);
                fputs(LoadError,fh);
              }

            } while(cbRead2);

            WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_MBWRITTEN),MPFROMLONG(writtenB));
            /*  mark EOF in pipe */        
            ungetc(EOF,pipe);
            /* Tell the PM wrapper that all the data is transfered to cdrecord */
            WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_FIXATING),MPFROMLONG(lNoFix));            
            /* Wait for cdrecord process to end */
            rc=pclose(pipe);
          
            DosClose(hpR2);
        
          }
        }
      }/* if(!DosDupHandle(HF_STDERR, &hfSave)) */
      DosWaitChild(0,DCWW_WAIT,&ChildRC,&pidChild,0);

      free(ptrLocalMem);
      //  DosFreeMem(pvSharedMem);
      if(fh) {
        sprintf(achBuf,"CDRecord returned: %d\n",rc);
        fputs(achBuf,fh);
        fclose(fh);
      }
   
  /* Send msg. to the notification window */
  WinPostMsg(hwndNotify,WM_APPTERMINATENOTIFY,MPFROMLONG(ACKEY_ONTHEFLY),MPFROMSHORT(rc));
}