Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Системное программирование и WinAPI > Запуск EXEшника


Автор: sOckets 27.8.2006, 03:30
Мне нужно запустить EXEшник , что лежит в папке с исполняемым файлом....куда копать ? уже замучасля...
вот что пробовал
Код

// WORK_BUFFER у меня "file.exe"
// file.exe присутсвует в папке...в чём трабла...хз
        error("начало");
        GetCurrentDirectory(sizeof(WORK_BUFFER)-1, WORK_BUFFER);
        error(WORK_BUFFER);
        strcpy(WORK_BUFFER,strstr(cmd,"+")+1);
        error(WORK_BUFFER);
        for (i = 0; i <= sizeof(WORK_BUFFER)-1; i++) if (WORK_BUFFER[i]=='\\') WORK_BUFFER[i]='/';
        error(WORK_BUFFER);        
        check =    WinExec(WORK_BUFFER,NULL);
        if (check > 31)
        {
            error("процесс успешно запущен...");
        } else {
            error("не могу запустить процесс...");
        }

Автор: Rickert 27.8.2006, 05:46
Копай в сторону ShellExecute()

Автор: BUGOR 27.8.2006, 07:18
или CreateProcess

Автор: sOckets 27.8.2006, 12:46
дайте примерчик smile

Добавлено @ 12:47 
И CreateProcess и ShellExecute пробовал....ничё не пашет..дело в том что я имя файл получаю с помошью GetCurretDirectory а там одинарные слешы , а в CreateProcess и ShellExecute нужны двойные...в общем кто может , примерчик покажите...

Автор: Damarus 27.8.2006, 13:11
Цитата(ilovewinsocks @  27.8.2006,  04:30 Найти цитируемый пост)
Мне нужно запустить EXEшник , что лежит в папке с исполняемым файлом....куда копать ?

 smile  smile  smile 
Код

WinExec("file.exe", SW_SHOWNORMAL);

 MSDN надо читать smile 

Цитата(ilovewinsocks @  27.8.2006,  13:46 Найти цитируемый пост)
И CreateProcess и ShellExecute пробовал....ничё не пашет..дело в том что я имя файл получаю с помошью GetCurretDirectory а там одинарные слешы , а в CreateProcess и ShellExecute нужны двойные...

Где это написано smile 

Автор: sOckets 27.8.2006, 13:31
Код

CreateProcess(NULL, "\"C:\\Program Files\\MyApp.exe\" -L -S", ...)


про ShellExecute что-то не нашёл...=\ 
ну что кто примерчик даст ?

Автор: Damarus 27.8.2006, 13:47
Цитата(ilovewinsocks @  27.8.2006,  14:31 Найти цитируемый пост)
про ShellExecute что-то не нашёл...=\ ну что кто примерчик даст ?

Код

ShellExecute(NULL, "open", "\"C:\\Program Files\\MyApp.exe\"", "-L -S", NULL, SW_SHOWNORMAL);


Но про запуск из той же папки я выше написал.

Автор: sOckets 27.8.2006, 15:40
не пашет =\

Автор: sOckets 27.8.2006, 15:57
Народ...ну дайте мне 100% рабочий сорц =\

Автор: _hunter 28.8.2006, 10:48
Цитата(ilovewinsocks @  27.8.2006,  15:57 Найти цитируемый пост)
Народ...ну дайте мне 100% рабочий сорц =\

это тебе в раздел "работа" нужно постить...

Автор: VectorMan 29.8.2006, 11:32
вроде робит  smile 

Код


bool ExecFromAppDirectory(const char* exefile)
{
  int c;
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  char buf [MAX_PATH];

  ZeroMemory(buf, MAX_PATH);
  
  c = GetModuleFileName(NULL, buf, MAX_PATH);
  
  strncpy(strrchr(buf, '\\') + 1, exefile, MAX_PATH - c - 1);
    
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);

  if(CreateProcess(buf, NULL, NULL, NULL, FALSE,
      NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
  {
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    return true;
  }
  else
    return false;

}




Автор: Damarus 30.8.2006, 17:33
VectorMan, это изобретение велосипеда.

ilovewinsocks, чем тебе WinExec не нравится. MSDN:
Цитата

WinExec

..................

lpCmdLine 
[in] Pointer to a null-terminated character string that contains the command line (file name plus optional parameters) for the application to be executed. If the name of the executable file in the lpCmdLine parameter does not contain a directory path, the system searches for the executable file in this sequence:

  • The directory from which the application loaded.
  • The current directory. 
  • The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.
  • The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.
  • The directories listed in the PATH environment variable.



Или CreateProcess:
Цитата

CreateProcess

..................

lpCommandLine 
[in, out] Pointer to a null-terminated string that specifies the command line to execute. The maximum length of this string is 32K characters.
   Windows 2000:  The maximum length of this string is MAX_PATH characters.

The Unicode version of this function, CreateProcessW, will fail if this parameter is a const string.

The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line.

If both lpApplicationName and lpCommandLine are non-NULL, the null-terminated string pointed to by lpApplicationName specifies the module to execute, and the null-terminated string pointed to by lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line.

If lpApplicationName is NULL, the first white-space – delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. If the file name does not contain a directory path, the system searches for the executable file in the following sequence:

  • The directory from which the application loaded.
  • The current directory for the parent process. 
  • The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
  • The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System. 
  • The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. 
  • The directories that are listed in the PATH environment variable.


Автор: chozen 30.8.2006, 23:08
Народ, вы что???

Если экзешник находится в той же папке, что и процесс, инициировавший запуск, не надо указывать никакаго пути...

ИМХО:
WinExec - слишком глупо...
ShellExecute - самое то
CreateProcess - половина параметров не нужно для обыденных случаев

Автор: sOckets 1.9.2006, 19:20
chozen  smile 

Автор: MoZy 1.9.2006, 21:20
 smile  spawnl(0,"любой.exe",NULL);

Автор: Greeen 1.9.2006, 23:01
ilovewinsocks, дык тебе ж Damarus, давал пример с ShellExecute.
Уф блин, держи 
Код
ShellExecute(NULL, "open", "SomeExe.exe", NULL, NULL, SW_SHOWNORMAL);

Автор: GremlinProg 1.9.2006, 23:04
Код

    CHAR path[MAX_PATH];
    sprintf(path,"%.*s\\your_executable.exe",strrchr(argv[0],'\\') - argv[0],argv[0]);
    ShellExecute(0,0,path,0,0,SW_SHOW);

ilovewinsocks, если это не работает, значит проблема в том, что ты чего-то сам не правильно делаешь. Самое первое: лежит ли прога в текущей директории, второе: CmdLine содержит ковычки в винапп, лучше использовать argv, третье: не поврежден ли экзешник. Пока больше в голову ни чего не приходит.

Автор: GremlinProg 1.9.2006, 23:22
Конкретизируй проблему: все данные команды(CreateProcess, ShellExecute...) только запускают файл на исполнение, так что если после запуска ты ожидаешь какой-то его выход, то необходимо подождать, пока приложение выполнится, в этом случае нужно использовать CreateProcess и WaitForSingleObject

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)