C spawn process windows

Функции _spawn, _wspawn _spawn, _wspawn Functions

Каждая из функций _spawn создает и запускает новый процесс: Each of the _spawn functions creates and executes a new process:

Буквы в конце имени функции определяют вариацию. The letters at the end of the function name determine the variation.

Письмо Letter Variant Variant
e envp , массив указателей на параметры среды, передается в новый процесс. envp , array of pointers to environment settings, is passed to new process.
l Аргументы командной строки передаются по отдельности в функцию _spawn . Command-line arguments are passed individually to _spawn function. Обычно этот суффикс используется, когда число параметров нового процесса известно заранее. This suffix is typically used when a number of parameters to a new process is known in advance.
p Переменная среды PATH используется для поиска файла для выполнения. PATH environment variable is used to find the file to execute.
v argv , массив указателей на аргументы командной строки, передается в функцию _spawn . argv , array of pointers to command-line arguments, is passed to _spawn function. Обычно этот суффикс используется, когда число параметров нового процесса не постоянно. This suffix is typically used when a number of parameters to a new process is variable.

Комментарии Remarks

Каждая из функций _spawn создает и выполняет новый процесс. 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. Функции _wspawn представляют собой версии функций _spawn для расширенных символов и не обрабатывают многобайтовые строки. The _wspawn functions are wide-character versions of the _spawn functions; they do not handle multibyte-character strings. В противном случае функции _wspawn ведут себя точно так же, как аналогичные функции _spawn . Otherwise, the _wspawn functions behave identically to their _spawn counterparts.

Универсальное текстовое сопоставление функций Generic-Text Routine Mappings

Процедура Tchar.h Tchar.h routine _UNICODE и _MBCS не определены _UNICODE and _MBCS not defined _MBCS определено _MBCS defined _UNICODE определено _UNICODE defined
_tspawnl _spawnl _spawnl _wspawnl
_tspawnle _spawnle _spawnle _wspawnle
_tspawnlp _spawnlp _spawnlp _wspawnlp
_tspawnlpe _spawnlpe _spawnlpe _wspawnlpe
_tspawnv _spawnv _spawnv _wspawnv
_tspawnve _spawnve _spawnve _wspawnve
_tspawnvp _spawnvp _spawnvp _wspawnvp
_tspawnvpe _spawnvpe _spawnvpe _wspawnvpe

Для загрузки и выполнения нового процесса необходимо обеспечить достаточно памяти. Enough memory must be available for loading and executing the new process. Аргумент mode определяет действие, предпринимаемое вызывающим процессом перед вызовом функции _spawn и во время ее выполнения. The mode argument determines the action taken by the calling process before and during _spawn . В файле Process.h определяются следующие значения аргумента mode : The following values for mode are defined in Process.h:

Значение Value Описание Description
_P_OVERLAY Перекрывает вызывающий процесс новым процессом, уничтожая вызывающий процесс (тот же эффект, что и при вызовах функций _exec ). Overlays a calling process with a new process, destroying the calling process (same effect as _exec calls).
_P_WAIT Приостанавливает вызывающий поток до тех пор, пока не будет завершено выполнение нового процесса (синхронная функция _spawn ). Suspends a calling thread until execution of the new process is complete (synchronous _spawn ).
_P_NOWAIT или _P_NOWAITO _P_NOWAIT or _P_NOWAITO Продолжает выполнять вызывающий процесс параллельно с новым процессом (асинхронная функция _spawn ). Continues to execute a calling process concurrently with the new process (asynchronous _spawn ).
_P_DETACH Продолжает выполнять вызывающий процесс; новый процесс выполняется в фоновом режиме без доступа к консоли или клавиатуре. Continues to execute the calling process; the new process is run in the background with no access to the console or keyboard. Вызовы функции _cwait для нового процесса завершаются ошибкой (асинхронная функция _spawn ). Calls to _cwait against the new process fail (asynchronous _spawn ).

Аргумент cmdname определяет файл, который выполняется как новый процесс и может указывать полный путь (от корневого каталога), частичный путь (из текущего рабочего каталога) или просто имя файла. 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 file name. Если cmdname не имеет расширения имени файла или не заканчивается точкой (.), функция _spawn сначала проверяет расширение COM, затем EXE, BAT и, наконец, CMD. If cmdname does not have a file name extension or does not end with a period (.), the _spawn function first tries the .com file name extension and then the .exe file name extension, the .bat file name extension, and finally the .cmd file name extension.

Если параметр cmdname имеет расширение имени файла, для поиска используется только это расширение. If cmdname has a file name extension, only that extension is used. Если cmdname заканчивается точкой, вызванная функция _spawn выполняет поиск cmdname без расширения имени файла. If cmdname ends with a period, the _spawn call searches for cmdname with no file name extension. Функции _spawnlp , _spawnlpe , _spawnvp и _spawnvpe выполняют поиск cmdname (используя те же процедуры) в каталогах, указанных в переменной среды PATH . The _spawnlp , _spawnlpe , _spawnvp , and _spawnvpe functions search for cmdname (using the same procedures) in the directories specified by the PATH environment variable.

Если cmdname содержит описатель диска или какие-либо косые черты (т. е. представляет собой относительный путь), функция _spawn выполняет поиск только указанного файла, а не пути. 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.

Раньше некоторые из этих функций присваивали параметру errno нулевое значение в случае успеха, теперь при успешном результате значение errno остается неизменным, как указано в стандарте С. In the past, some of these functions set errno to zero on success; the current behavior is to leave errno untouched on success, as specified by the C standard. Если нужно эмулировать старое поведение, перед вызовом этих функций присвойте параметру errno нулевое значение. If you need to emulate the old behavior, set errno to zero just before calling these functions.

Чтобы обеспечить правильную инициализацию и прекращение перекрытия, не используйте функцию setjmp или longjmp для входа в подпрограмму перекрытия или выхода из нее. 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

Для передачи аргументов в новый процесс задайте один или нескольких указателей на символьные строки как аргументы вызова функции _spawn . 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. Общая длина строк, формирующих список аргументов для нового процесса, не должна превышать 1024 байтов. The combined length of the strings forming the argument list for the new process must not exceed 1024 bytes. Символ null, завершающий строку (‘\0’), для каждой строки не учитывается, однако учитываются символы пробелов (вставляемые автоматически для разделения аргументов). The terminating null character (‘\0’) for each string is not included in the count, but space characters (automatically inserted to separate arguments) are included.

Пробелы, встроенные в строки, могут вызывать непредвиденное поведение. Например, если передать в функцию _spawn строку «hi there» , это приведет к тому, что новый процесс получит два аргумента: «hi» и «there» . Spaces embedded in strings may cause unexpected behavior; for example, passing _spawn the string «hi there» will result in the new process getting two arguments, «hi» and «there» . Если предполагалось, что новый процесс должен открыть файл с именем hi there, произойдет сбой процесса. If the intent was to have the new process open a file named «hi there», the process would fail. Этого можно избежать, заключив строку в кавычки: «\»hi there\»» . You can avoid this by quoting the string: «\»hi there\»» .

Не передавайте данные, вводимые пользователем, в функцию _spawn , не выбрав это содержимое явно. Do not pass user input to _spawn without explicitly checking its content. _spawn вызывает функцию CreateProcess, поэтому имейте в виду, что неполные пути могут привести к потенциальным уязвимостям безопасности. _spawn will result in a call to CreateProcess so keep in mind that unqualified path names could lead to potential security vulnerabilities.

Указатели аргументов можно передавать как отдельные параметры (в функциях _spawnl , _spawnle , _spawnlp и _spawnlpe ) или как массивы указателей (в функциях _spawnv , _spawnve , _spawnvp и _spawnvpe ). 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 ). В порожденный процесс необходимо передавать хотя бы один аргумент, arg0 или argv [0]. 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.

Вызовы функций _spawnl , _spawnle , _spawnlp и _spawnlpe обычно используются, если число аргументов известно заранее. The _spawnl , _spawnle , _spawnlp , and _spawnlpe calls are typically used in cases where the number of arguments is known in advance. Аргумент arg0 обычно является указателем на параметр cmdname . The arg0 argument is usually a pointer to cmdname . Аргументы arg1 – argn являются указателями на строки символов, которые образуют новый список аргументов. The arguments arg1 through argn are pointers to the character strings forming the new argument list. После argn должен следовать указатель на NULL, отмечающий конец списка аргументов. Following argn , there must be a NULL pointer to mark the end of the argument list.

Функции _spawnv , _spawnve , _spawnvp и _spawnvpe можно вызывать, если число аргументов в новом процессе не определено. The _spawnv , _spawnve , _spawnvp , and _spawnvpe calls are useful when there is a variable number of arguments to the new process. Указатели на аргументы передаются как массив argv . Pointers to the arguments are passed as an array, argv . Аргумент argv [0] обычно является указателем на путь в реальном режиме или на имя программы в защищенном режиме, а аргументы с argv [1] по argv [ n ] — это указатели на символьные строки, формирующие новый список аргументов. 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. Аргумент argv [ n +1] должен быть указателем на NULL, отмечающим конец списка аргументов. The argument argv [ n +1] must be a NULL pointer to mark the end of the argument list.

Среда порожденного процесса Environment of the Spawned Process

Файлы, открытые во время вызова функции _spawn , остаются открытыми в новом процессе. Files that are open when a _spawn call is made remain open in the new process. В вызовах _spawnl , _spawnlp , _spawnv и _spawnvp новый процесс наследует среду вызывающего процесса. In the _spawnl , _spawnlp , _spawnv , and _spawnvp calls, the new process inherits the environment of the calling process. Вызовы функций _spawnle , _spawnlpe , _spawnve и _spawnvpe изменяют среду для нового процесса, передавая список параметров среды с помощью аргумента envp . 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. Аргумент envp — это массив указателей символов, каждый элемент которого (за исключением последнего) указывает на строку, завершающуюся символом NULL, определенную в переменной среды. 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. Такие строки обычно имеют вид NAME = value , где NAME — это имя переменной среды, а value — строковое значение, задаваемое для данной переменной. 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. (Обратите внимание, что value не заключено в двойные кавычки.) Последний элемент envp массива должен иметь значение NULL. (Note that value is not enclosed in double quotation marks.) The final element of the envp array should be NULL. Если же значение самого параметра envp — NULL, порожденный процесс наследует параметры среды родительского процесса. When envp itself is NULL, the spawned process inherits the environment settings of the parent process.

Функции _spawn могут передавать все сведения об открытых файлах, включая режим преобразования, в новый процесс. The _spawn functions can pass all information about open files, including the translation mode, to the new process. Эти сведения передаются в режиме реального времени через запись C_FILE_INFO в среде. 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. Если же функция _spawn порождает процесс, отличный от C, эта запись сохраняется в среде. 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.

Перед вызовом функции fflush необходимо явно сбросить (используя ключевое слово _flushall или _spawn ) или закрыть все потоки. You must explicitly flush (using fflush or _flushall ) or close any stream before calling a _spawn function.

В новых процессах, создаваемых при вызове подпрограмм _spawn , сигнальные параметры не сохраняются. New processes created by calls to _spawn routines do not preserve signal settings. Вместо этого порожденный процесс сбрасывает параметры сигнала по умолчанию. Instead, the spawned process resets signal settings to the default.

Перенаправление выходных данных Redirecting Output

Если при вызове функции _spawn из библиотеки DLL или приложения с графическим интерфейсом вы хотите перенаправить выходные данные в канал, можно выбрать один из двух вариантов: If you are calling _spawn from a DLL or a GUI application and want to redirect the output to a pipe, you have two options:

Воспользуйтесь API Win32, чтобы создать канал, вызовите функцию AllocConsole, задайте значения обработки в структуре запуска и вызовите функцию CreateProcess. Use the Win32 API to create a pipe, then call AllocConsole, set the handle values in the startup structure, and call CreateProcess.

Читайте также:  Chromedriver windows 10 64 bit
Оцените статью