Solved

how do I run a program from my c-program?

Posted on 1997-10-25
2
288 Views
Last Modified: 2012-08-14
I just wonder how to run an external program from within my c-program. It would be nice if it worked under win 3.1 also.
0
Comment
Question by:davvan
2 Comments
 
LVL 3

Accepted Solution

by:
eugenem earned 30 total points
ID: 1172055

_exec, _wexec Functions
Each of the functions in this family loads and executes a new process.

_execl, _wexecl
 _execv, _wexecv
 
_execle, _wexecle
 _execve, _wexecve
 
_execlp, _wexeclp
 _execvp, _wexecvp
 
_execlpe, _wexeclpe
 _execvpe, _wexecvpe
 




The letter(s) at the end of the function name determine the variation.

_exec Function Suffix
 
Description
 

 
e
 envp, array of pointers to environment settings, is passed to new process.
 
l
 Command-line arguments are passed individually to _exec function. Typically used when number of parameters to new process is known in advance.
 
p
 PATH environment variable is used to find file to execute.
 
v
 argv, array of pointers to command-line arguments, is passed to _exec. Typically used when number of parameters to new process is variable.
 




Remarks

Each of the _exec functions loads and execute a new process. All _exec functions use the same operating-system function. The _exec functions automatically handle multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use. The _wexec functions are wide-character versions of the _exec functions. The _wexec functions behave identically to their _exec family counterparts except that they do not handle multibyte-character strings.

Generic-Text Routine Mappings:
 

 
TCHAR.H Routine
 _UNICODE & _MBCS Not Defined
 _MBCS Defined
 _UNICODE Defined
 

 
_texecl
 _execl
 _execl
 _wexecl
 
_texecle
 _execle
 _execle
 _wexecle
 
_texeclp
 _execlp
 _execlp
 _wexeclp
 
_texeclpe
 _execlpe
 _execlpe
 _wexeclpe
 
_texecv
 _execv
 _execv
 _wexecv
 
_texecve
 _execve
 _execve
 _wexecve
 
_texecvp
 _execvp
 _execvp
 _wexecvp
 
_texecvpe
 _execvpe
 _execvpe
 _wexecvpe
 




When a call to an _exec function is successful, the new process is placed in the memory previously occupied by the calling process. Sufficient memory must be available for loading and executing the new process.

The cmdname parameter specifies the file to be executed as the new process. It can specify a full path (from the root), a partial path (from the current working directory), or a filename. If cmdname does not have a filename extension or does not end with a period (.), the _exec function searches for the named file. If the search is unsuccessful, it tries the same base name with the .COM extension and then with the .EXE, .BAT, and .CMD extensions. If cmdname has an extension, only that extension is used in the search. If cmdname ends with a period, the _exec function searches for cmdname with no extension. _execlp, _execlpe, _execvp, and _execvpe search for cmdname (using the same procedures) in the directories specified by the PATH environment variable. If cmdname contains a drive specifier or any slashes (that is, if it is a relative path), the _exec call searches only for the specified file; the path is not searched.

Parameters are passed to the new process by giving one or more pointers to character strings as parameters in the _exec call. These character strings form the parameter list for the new process. The combined length of the inherited environment settings and the strings forming the parameter list for the new process must not exceed 32K bytes. The terminating null character ('\0') for each string is not included in the count, but space characters (inserted automatically to separate the parameters) are counted.

The argument pointers can be passed as separate parameters (in _execl, _execle, _execlp, and _execlpe) or as an array of pointers (in _execv, _execve, _execvp, and _execvpe). At least one parameter, arg0, must be passed to the new process; this parameter is argv[0] of the new process. Usually, this parameter is a copy of cmdname. (A different value does not produce an error.)

The _execl, _execle, _execlp, and _execlpe calls are typically used when the number of parameters is known in advance. The parameter arg0 is usually a pointer to cmdname. The parameters arg1 through argn point to the character strings forming the new parameter list. A null pointer must follow argn to mark the end of the parameter list.

The _execv, _execve, _execvp, and _execvpe calls are useful when the number of parameters to the new process is variable. Pointers to the parameters are passed as an array, argv. The parameter argv[0] is usually a pointer to cmdname. The parameters argv[1] through argv[n] point to the character strings forming the new parameter list. The parameter argv[n+1] must be a NULL pointer to mark the end of the parameter list.

Files that are open when an _exec call is made remain open in the new process. In _execl, _execlp, _execv, and _execvp calls, the new process inherits the environment of the calling process. _execle, _execlpe, _execve, and _execvpe calls alter the environment for the new process by passing a list of environment settings through the envp parameter. envp is an array of character pointers, each element of which (except for the final element) points to a null-terminated string defining an environment variable. Such a string usually has the form NAME=value where NAME is the name of an environment variable and value is the string value to which that variable is set. (Note that value is not enclosed in double quotation marks.) The final element of the envp array should be NULL. When envp itself is NULL, the new process inherits the environment settings of the calling process.

A program executed with one of the _exec functions is always loaded into memory as if the "maximum allocation" field in the program's .EXE file header were set to the default value of 0xFFFFH. You can use the EXEHDR utility to change the maximum allocation field of a program; however, such a program invoked with one of the _exec functions may behave differently from a program invoked directly from the operating-system command line or with one of the _spawn functions.

The _exec calls do not preserve the translation modes of open files. If the new process must use files inherited from the calling process, use the _setmode routine to set the translation mode of these files to the desired mode. You must explicitly flush (using fflush or _flushall) or close any stream before the _exec function call. Signal settings are not preserved in new processes that are created by calls to _exec routines. The signal settings are reset to the default in the new process.

Example




/* EXEC.C illustrates the different versions of exec including:
 *      _execl          _execle          _execlp          _execlpe
 *      _execv          _execve          _execvp          _execvpe
 *
 * Although EXEC.C can exec any program, you can verify how
 * different versions handle arguments and environment by
 * compiling and specifying the sample program ARGS.C. See
 * SPAWN.C for examples of the similar spawn functions.
 */

#include <stdio.h>
#include <conio.h>
#include <process.h>

char *my_env[] =                /* Environment for exec?e */
{
   "THIS=environment will be",
   "PASSED=to new process by",
   "the EXEC=functions",
   NULL
};

void main()
{
   char *args[4], prog[80];
   int ch;

   printf( "Enter name of program to exec: " );
   gets( prog );
   printf( " 1. _execl  2. _execle  3. _execlp  4. _execlpe\n" );
   printf( " 5. _execv  6. _execve  7. _execvp  8. _execvpe\n" );
   printf( "Type a number from 1 to 8 (or 0 to quit): " );
   ch = _getche();
   if( (ch < '1') || (ch > '8') )
       exit( 1 );
   printf( "\n\n" );

   /* Arguments for _execv? */
   args[0] = prog;
   args[1] = "exec??";
   args[2] = "two";
   args[3] = NULL;

   switch( ch )
   {
   case '1':
      _execl( prog, prog, "_execl", "two", NULL );
      break;
   case '2':
      _execle( prog, prog, "_execle", "two", NULL, my_env );
      break;
   case '3':
      _execlp( prog, prog, "_execlp", "two", NULL );
      break;
   case '4':
      _execlpe( prog, prog, "_execlpe", "two", NULL, my_env );
      break;
   case '5':
      _execv( prog, args );
      break;
   case '6':
      _execve( prog, args, my_env );
      break;
   case '7':
      _execvp( prog, args );
      break;
   case '8':
      _execvpe( prog, args, my_env );
      break;
   default:
      break;
   }

   /* This point is reached only if exec fails. */
   printf( "\nProcess was not execed." );
   exit( 0 );
}
 
Process and Environment Control Routines

See Also abort, atexit, exit, _onexit, _spawn Function Overview, system


_spawn, _wspawn Functions
Each of the _spawn functions creates and executes a new process.

_spawnl, _wspawnl _spawnv, _wspawnv
_spawnle, _wspawnle _spawnve, _wspawnve
_spawnlp, _wspawnlp _spawnvp, _wspawnvp
_spawnlpe, _wspawnlpe _spawnvpe, _wspawnvpe




The letter(s) at the end of the function name determine the variation.

_spawn
Function
Suffix
 

Description
 

 
e
 envp, array of pointers to environment settings, is passed to new process.
 
l
 Command-line arguments are passed individually to _spawn function. This suffix is typically used when number of parameters to new process is known in advance
 
p
 PATH environment variable is used to find file to execute.
 
v
 argv, array of pointers to command-line arguments, is passed to _spawn function. This suffix is typically used when number of parameters to new process is variable.
 




Remarks

The _spawn functions each create and execute a new process. They automatically handle multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use. The _wspawn functions are wide-character versions of the _spawn functions; they do not handle multibyte-character strings. Otherwise, the _wspawn functions behave identically to their _spawn counterparts.

Generic-Text Routine Mappings
 

 
TCHAR.H Routine
 _UNICODE & _MBCS Not Defined
 _MBCS Defined
 _UNICODE Defined
 

 
_tspawnl
 _spawnl
 _spawnl
 _wspawnl
 
_tspawnle
 _spawnle
 _spawnle
 _spawnle
 
_tspawnlp
 _spawnlp
 _spawnlp
 _spawnlp
 
_tspawnlpe
 _spawnlpe
 _spawnlpe
 _spawnlpe
 
_tspawnv
 _spawnv
 _spawnv
 _spawnv
 
_tspawnve
 _spawnve
 _spawnve
 _spawnve
 
_tspawnvp
 _spawnvp
 _spawnvp
 _spawnvp
 
_tspawnvpe
 _spawnvpe
 _spawnvpe
 _spawnvpe
 




Enough memory must be available for loading and executing the new process. The mode argument determines the action taken by the calling process before and during _spawn. The following values for mode are defined in PROCESS.H:

_P_OVERLAY Overlays calling process with new process, destroying the calling process (same effect as _exec calls).

_P_WAIT Suspends calling thread until execution of new process is complete (synchronous _spawn).

_P_NOWAIT or _P_NOWAITO Continues to execute calling process concurrently with new process (asynchronous _spawn).

_P_DETACH Continues to execute the calling process; new process is run in the background with no access to the console or keyboard. Calls to _cwait against the new process will fail (asynchronous _spawn).

The cmdname argument specifies the file that is executed as the new process and can specify a full path (from the root), a partial path (from the current working directory), or just a filename. If cmdname does not have a filename extension or does not end with a period (.), the _spawn function first tries the .COM extension, then the .EXE extension, the .BAT extension, and finally the .CMD extension.

If cmdname has an extension, only that extension is used. If cmdname ends with a period, the _spawn call searches for cmdname with no extension. The _spawnlp, _spawnlpe, _spawnvp, and _spawnvpe functions search for cmdname (using the same procedures) in the directories specified by the PATH environment variable.

If cmdname contains a drive specifier or any slashes (that is, if it is a relative path), the _spawn call searches only for the specified file; no path searching is done.

Note To ensure proper overlay initialization and termination, do not use the setjmp or longjmp function to enter or leave an overlay routine.

Arguments for the Spawned Process

To pass arguments to the new process, give one or more pointers to character strings as arguments in the _spawn call. These character strings form the argument list for the spawned process. The combined length of the strings forming the argument list for the new process must not exceed 1024 bytes. The terminating null character ('\0') for each string is not included in the count, but space characters (automatically inserted to separate arguments) are included.

You can pass argument pointers as separate arguments (in _spawnl, _spawnle, _spawnlp, and _spawnlpe) or as an array of pointers (in _spawnv, _spawnve, _spawnvp, and _spawnvpe). You must pass at least one argument, arg0 or argv[0], to the spawned process. By convention, this argument is the name of the program as you would type it on the command line. A different value does not produce an error.

The _spawnl, _spawnle, _spawnlp, and _spawnlpe calls are typically used in cases where the number of arguments is known in advance. The arg0 argument is usually a pointer to cmdname. The arguments arg1 through argn are pointers to the character strings forming the new argument list. Following argn, there must be a NULL pointer to mark the end of the argument list.

The _spawnv, _spawnve, _spawnvp, and _spawnvpe calls are useful when there is a variable number of arguments to the new process. Pointers to the arguments are passed as an array, argv. The argument argv[0] is usually a pointer to a path in real mode or to the program name in protected mode, and argv[1] through argv[n] are pointers to the character strings forming the new argument list. The argument argv[n +1] must be a NULL pointer to mark the end of the argument list.

Environment of the Spawned Process

Files that are open when a _spawn call is made remain open in the new process. In the _spawnl, _spawnlp, _spawnv, and _spawnvp calls, the new process inherits the environment of the calling process. You can use the _spawnle, _spawnlpe, _spawnve, and _spawnvpe calls to alter the environment for the new process by passing a list of environment settings through the envp argument. The argument envp is an array of character pointers, each element (except the final element) of which points to a null-terminated string defining an environment variable. Such a string usually has the form NAME=value where NAME is the name of an environment variable and value is the string value to which that variable is set. (Note that value is not enclosed in double quotation marks.) The final element of the envp array should be NULL. When envp itself is NULL, the spawned process inherits the environment settings of the parent process.

The _spawn functions can pass all information about open files, including the translation mode, to the new process. This information is passed in real mode through the C_FILE_INFO entry in the environment. The startup code normally processes this entry and then deletes it from the environment. However, if a _spawn function spawns a non-C process, this entry remains in the environment. Printing the environment shows graphics characters in the definition string for this entry because the environment information is passed in binary form in real mode. It should not have any other effect on normal operations. In protected mode, the environment information is passed in text form and therefore contains no graphics characters.

You must explicitly flush (using fflush or _flushall) or close any stream before calling a _spawn function.

You can control whether the open file information of a process is passed to its spawned processes. The external variable _fileinfo (declared in STDLIB.H) controls the passing of C_FILE_INFO information. If _fileinfo is 0 (the default), the C_FILE_INFO information is not passed to the new processes. If _fileinfo is not 0, C_FILE_INFO is passed to new processes. You can modify the default value of _fileinfo in one of two ways: link the supplied object file, FILEINFO.OBJ, into the program, or set the _fileinfo variable to a nonzero value directly in the C program.

New processes created by calls to _spawn routines do not preserve signal settings. Instead, the spawned process resets signal settings to the default.

Example




/* SPAWN.C: This program accepts a number in the range
 * 1-8 from the command line. Based on the number it receives,
 * it executes one of the eight different procedures that
 * spawn the process named child. For some of these procedures,
 * the CHILD.EXE file must be in the same directory; for
 * others, it only has to be in the same path.
 */

#include <stdio.h>
#include <process.h>

char *my_env[] =
{
   "THIS=environment will be",
   "PASSED=to child.exe by the",
   "_SPAWNLE=and",
   "_SPAWNLPE=and",
   "_SPAWNVE=and",
   "_SPAWNVPE=functions",
   NULL
};

void main( int argc, char *argv[] )
{
   char *args[4];

   /* Set up parameters to be sent: */
   args[0] = "child";
   args[1] = "spawn??";
   args[2] = "two";
   args[3] = NULL;

   if (argc <= 2)
   {
      printf( "SYNTAX: SPAWN <1-8> <childprogram>\n" );
      exit( 1 );
   }

   switch (argv[1][0])   /* Based on first letter of argument */
   {
   case '1':
      _spawnl( _P_WAIT, argv[2], argv[2], "_spawnl", "two", NULL );
      break;
   case '2':
      _spawnle( _P_WAIT, argv[2], argv[2], "_spawnle", "two",
               NULL, my_env );
      break;
   case '3':
      _spawnlp( _P_WAIT, argv[2], argv[2], "_spawnlp", "two", NULL );
      break;
   case '4':
      _spawnlpe( _P_WAIT, argv[2], argv[2], "_spawnlpe", "two",
                NULL, my_env );
      break;
   case '5':
      _spawnv( _P_OVERLAY, argv[2], args );
      break;
   case '6':
      _spawnve( _P_OVERLAY, argv[2], args, my_env );
      break;
   case '7':
      _spawnvp( _P_OVERLAY, argv[2], args );
      break;
   case '8':
      _spawnvpe( _P_OVERLAY, argv[2], args, my_env );
      break;
   default:
      printf( "SYNTAX: SPAWN <1-8> <childprogram>\n" );
      exit( 1 );
   }
   printf( "from SPAWN!\n" );
}
Output




SYNTAX: SPAWN <1-8> <childprogram>
Process and Environment Control Routines

See Also abort, atexit, _exec Functions, exit, _flushall, _getmbcp, _onexit, _setmbcp, system

0
 
LVL 1

Expert Comment

by:TheMadManiac
ID: 1172056
and if you just need to call a program without setting environment and others, try system :)

system("file_to_execute args_to_pass");

for example:

system("dir *.*");
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now