Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.snto-msu.net/showflat.php?Number=6947229&src=arc&showlite=
Дата изменения: Unknown
Дата индексирования: Wed Apr 13 03:16:03 2016
Кодировка: Windows-1251
Как запустить экзэшник визуалка 2005 под винду - Public forum of MSU united student networks
Root | Google | Yandex | Mail.ru | Kommersant | Afisha | LAN Support
  
Technical >> Development (Archive)

Страницы: 1
CrUeL
Without LimitS

Рег.: 30.03.2003
Сообщений: 762
Из: Москва
Рейтинг: -26
  Как запустить экзэшник визуалка 2005 под винду
      02.12.2007 00:04
-6

Вот возник такой вопрос, просто из стандартных библиотеках не нашел, подскажите плз.



Let's love the world...
Yorik

Рег.: 01.09.2005
Сообщений: 2476
Из: Москва
Рейтинг: 633
  Re: Как запустить экзэшник визуалка 2005 под винду [re: CrUeL]
      02.12.2007 00:18
 

Хорошо сказал. Ничего не понятно.

Дай догадаюсь... Может, скомпилить со статической линковкой?

abv

Рег.: 21.09.2007
Сообщений: 6924
Рейтинг: 6747
  Re: Как запустить экзэшник визуалка 2005 под винду [re: CrUeL]
      02.12.2007 00:25
 

[telepat-mode=on]ты хочешь запустить на выполнение из своей программы другую? типа аналога exec-a в си? а на каком языке пишешь?[telepat-mode=off]



зимой и летом велозона
CrUeL
Without LimitS

Рег.: 30.03.2003
Сообщений: 762
Из: Москва
Рейтинг: -26
  Re: Как запустить экзэшник визуалка 2005 под винду [re: abv]
      02.12.2007 00:33
 

c++
надо запустить exe файл из мвоей программы, exec не находит со стандартними библиотеками понять не могу.



Let's love the world...
abv

Рег.: 21.09.2007
Сообщений: 6924
Рейтинг: 6747
  Re: Как запустить экзэшник визуалка 2005 под винду [re: CrUeL]
      02.12.2007 00:35
 

и в мсдн-е тоже хочешь сказать ничего не нашел?



зимой и летом велозона
CrUeL
Without LimitS

Рег.: 30.03.2003
Сообщений: 762
Из: Москва
Рейтинг: -26
  Re: Как запустить экзэшник визуалка 2005 под винду [re: abv]
      02.12.2007 00:37
-3

я не спрашиваю, где искать я прошу подсказать как это сделать.



Let's love the world...
abv

Рег.: 21.09.2007
Сообщений: 6924
Рейтинг: 6747
  Re: Как запустить экзэшник визуалка 2005 под винду [re: abv]
      02.12.2007 00:38
1

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vccrt/html/a261df93-206a-4fdc-b8ac-66aa7db83bc6.htm

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


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


Each _exec function loads and executes 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.

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 file name. If cmdname does not have a file name 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 file name extension and then with the .exe, .bat, and .cmd file name extensions. If cmdname has a file name extension, only that extension is used in the search. If cmdname ends with a period, the _exec function searches for cmdname with no file name 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 32 kilobytes. 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.

Note
Spaces embedded in strings may cause unexpected behavior; for example, passing _exec the string "hi there" will result in the new process getting two arguments, "hi" and "there". If the intent was to have the new process open a file named "hi there", the process would fail. You can avoid this by quoting the string: "\"hi there\"".
 
Security Note
Do not pass user input to _exec without explicitly checking its content. _exec will result in a call to CreateProcess so keep in mind that unqualified path names could lead to potential security vulnerabilities.
 

In Visual C++ 2005, the _exec functions validate their parameters. If expected parameters are null pointers, empty strings, or omitted, the _exec functions invoke the invalid parameter handler as described in Parameter Validation. If execution is allowed to continue, these functions set errno to EINVAL and return -1. No new process is executed.

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.

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.





// crt_exec.c
// Illustrates the different versions of exec, including
// _execl _execle _execlp _execlpe
// _execv _execve _execvp _execvpe
//
// Although CRT_EXEC.C can exec any program, you can verify how
// different versions handle arguments and environment by
// compiling and specifying the sample program CRT_ARGS.C. See
// "_spawn, _wspawn Functions" 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
};

int main( int ac, char* av[] )
{
char *args[4];
int ch;
if( ac != 3 ){
fprintf( stderr, "Usage: %s <program> <number (1-8)>\n", av[0] );
return;
}

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

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

// This point is reached only if exec fails.
printf( "\nProcess was not execed." );
exit( 0 );
}




зимой и летом велозона
CrUeL
Without LimitS

Рег.: 30.03.2003
Сообщений: 762
Из: Москва
Рейтинг: -26
  Re: Как запустить экзэшник визуалка 2005 под винду [re: abv]
      02.12.2007 00:52
 

спасиб



Let's love the world...
penartur2

Рег.: 16.06.2005
Сообщений: 54495
Рейтинг: 429
  Re: Как запустить экзэшник визуалка 2005 под винду [re: abv]
      02.12.2007 15:46
 

В ответ на:

Note
Spaces embedded in strings may cause unexpected behavior; for example, passing _exec the string "hi there" will result in the new process getting two arguments, "hi" and "there". If the intent was to have the new process open a file named "hi there", the process would fail. You can avoid this by quoting the string: "\"hi there\"".




Жесть.
А что, ничего приличного в вашем VC++ нет?



Я ушел на новый форум.
Там правовое государство. А еще можно удобно листать аплоад ;)
Yorik

Рег.: 01.09.2005
Сообщений: 2476
Из: Москва
Рейтинг: 633
  Re: Как запустить экзэшник визуалка 2005 под винду [re: penartur2]
      02.12.2007 15:52
 


 :grin:
ну ты даешь.
а в никсах не так же, хочешь сказать, умник?

penartur2

Рег.: 16.06.2005
Сообщений: 54495
Рейтинг: 429
  Re: Как запустить экзэшник визуалка 2005 под винду [re: Yorik]
      02.12.2007 16:37
 

Я ниябу, как там в никсах.
Но какого хрена, если одна моя программа передает в exec массив аргументов, а другая моя принимает из командной строки этот массив, который автоматически парсится и кладется в argc - я должен знать о том, как реализована командная строка, и о том, что, если в одном из аргументов есть пробел - мне надо этот аргумент заключить в кавычки, а кавычки, которые внутри - заэкранировать?



Я ушел на новый форум.
Там правовое государство. А еще можно удобно листать аплоад ;)
DarkGrayМодератор
Carpal Tunnel

Рег.: 30.09.2002
Сообщений: 31415
Рейтинг: 8952
  Re: Как запустить экзэшник визуалка 2005 под винду [re: penartur2]
      02.12.2007 17:04
 

потому что на командную строку и на все эти кавычки нет нормального единого стандарта

penartur2

Рег.: 16.06.2005
Сообщений: 54495
Рейтинг: 429
  Re: Как запустить экзэшник визуалка 2005 под винду [re: DarkGray]
      02.12.2007 17:16
 

Ну так тем более!
У меня есть массив аргументов, мне надо передать его другой программе.
И почему-то в том месте, где первая программа эти аргументы передает - ей надо задумываться о всех этих кавычках, на которые еще и стандарта единого нет - т.е. первая программа должна завязаться на какую-то конкретную реализацию аргументов командной строки.



Я ушел на новый форум.
Там правовое государство. А еще можно удобно листать аплоад ;)
DarkGrayМодератор
Carpal Tunnel

Рег.: 30.09.2002
Сообщений: 31415
Рейтинг: 8952
  Re: Как запустить экзэшник визуалка 2005 под винду [re: penartur2]
      02.12.2007 18:42
 

> У меня есть массив аргументов, мне надо передать его другой программе

так бери какую-нибудь стандартную технологию (например, xml) - да, передавай.

penartur2

Рег.: 16.06.2005
Сообщений: 54495
Рейтинг: 429
  Re: Как запустить экзэшник визуалка 2005 под винду [re: DarkGray]
      02.12.2007 19:12
 

Тем не менее, есть один уровень абстракции - командная строка, где команда вызывается такой строкой: /path/to/executable arg1 "arg 2 with spaces" arg3
и другой, над ним - где вызывается /path/to/executable с массивом аргументов arg1, arg 2 with spaces и arg3.
Какие аргументы есть в пользу того, чтобы прикладному софту, который, вроде как, везде работает именно с конкретными аргументами, а не с командной строкой - приходилось знать о том, как именно устроена эта командная строка, и спускаться на уровень ниже?
Почему эти *exec* настолько тупы, что не могут сами определить, что какие-то аргументы в данной реализации командной строки надо заэкранировать каким-то конкретным способом, почему об этом приходится думать разработчику и завязываться на конкретную реализацию ком.строки?



Я ушел на новый форум.
Там правовое государство. А еще можно удобно листать аплоад ;)
Fj_
Carpal Tunnel

Рег.: 12.09.2004
Сообщений: 8795
Рейтинг: 3287
  Re: Как запустить экзэшник визуалка 2005 под винду [re: penartur2]
      02.12.2007 23:26
1

Потому что эти exec - низкоуровневые функции. Совсем низкоуровневые. Хочешь единообразной передачи параметров - напиши свой враппер и хоть хмл гоняй, действительно.

Я не очень понимаю расстройства от того, что тебе не нужно ручками конкатенировать разные параметры в одну строчку. Вот такое удобство тебе предоставили, не хочешь - не пользуйся. Ну да, неортогональненько получается, но удобней же, чем если бы все параметры одной строкой принимались.



The data is the error (c)IIS FTP Server.
penartur2

Рег.: 16.06.2005
Сообщений: 54495
Рейтинг: 429
  Re: Как запустить экзэшник визуалка 2005 под винду [re: Fj_]
      03.12.2007 13:06
 

В ответ на:

Потому что эти exec - низкоуровневые функции. Совсем низкоуровневые



Если они "совсем низкоуровневые" - пусть принимают на вход только одну строку, в которой будет и путь к исполняемому файлу, и аргументы, должным образом заэкранированные. Зачем этот цирк с массивами аргументов?
А если уж говорим про разделение команды и аргументов - то пусть этот exec и позаботится о том, чтобы перед склеиванием всего этого в одну строку все заэкранировать.



Я ушел на новый форум.
Там правовое государство. А еще можно удобно листать аплоад ;)
Fj_
Carpal Tunnel

Рег.: 12.09.2004
Сообщений: 8795
Рейтинг: 3287
  Re: Как запустить экзэшник визуалка 2005 под винду [re: penartur2]
      03.12.2007 13:42
1

Я не очень понимаю расстройства от того, что тебе не нужно ручками конкатенировать разные параметры в одну строчку. Вот такое удобство тебе предоставили, не хочешь - не пользуйся. Ну да, неортогональненько получается, но удобней же, чем если бы все параметры одной строкой принимались.



The data is the error (c)IIS FTP Server.
Страницы: 1

Technical >> Development (Archive)

Дополнительная информация
0 зарегистрированных и 0 анонимных пользователей просматривают этот форум.

Модераторы:  DarkGray 

Печать темы

Права
      Вы можете создавать новые темы
      Вы можете отвечать на сообщения
      HTML отключен
      UBBCode включен

Рейтинг:
Просмотров темы:

Переход в