Saltar al contenido principal
Versión: Siguiente

SystemWorker

System workers allow the 4D code to call any external process (a shell command, PHP, etc.) on the same machine. Los trabajadores del sistema se llaman de forma asíncrona. Mediante el uso de retrollamadas, 4D hace posible la comunicación en ambos sentidos.

The SystemWorker class is available from the 4D class store.

Ejemplo

    // Windows example to get access to the ipconfig information
var $myWinWorker : 4D.SystemWorker
var $ipConfig : Text
$myWinWorker:= 4D.SystemWorker.new("ipconfig")
$ipConfig:=$myWinWorker.wait(1).response //timeout 1 second

// macOS example to change the permissions for a file on macOS
// chmod is the macOS command used to modify file access
var $myMacWorker : 4D.SystemWorker
$myMacWorker:= 4D.SystemWorker.new("chmod +x /folder/myfile.sh")

Resumen

| 4D.SystemWorker.new ( commandLine : Text { ; options : Object } ) : 4D.SystemWorker
creates and returns a 4D.SystemWorker object that will execute the commandLine you passed as parameter to launch an external process | | .closeInput()
closes the input stream (stdin) of the external process | | .commandLine : Text
contains the command line passed as parameter to the new() function | | .currentDirectory : 4D.Folder
contains the working directory in which the external process is executed | | .dataType : Text
contains the type of the response body content | | .encoding : Text
contains the encoding of the response body content | | .errors : Collection
contains a collection of 4D errors in case of execution error(s) if any | | .exitCode : Integer
contains the exit code returned by the external process | | .hideWindow : Boolean
can be used to hide the window of the DOS console or the window of the launched executable (Windows only) | | .pid : Integer
contains the process unique identifier of the external process at the system level | | .postMessage( message : Text)
.postMessage( messageBLOB : Blob)

allows you to write on the input stream (stdin) of the external process | | .response : Text
.response : Blob

contains the concatenation of all data returned once the request is terminated | | .responseError : Text
contains the concatenation of all the errors returned, once the request is terminated | | .terminate()
forces the SystemWorker to terminate its execution | | .terminated : Boolean
contains true if the external process is terminated | | .timeout : Integer
contains the duration in seconds before the external process will be killed if it is still alive | | .wait( {timeout : Real} ) : 4D.SystemWorker
waits until the end of the SystemWorker execution or the specified timeout |

4D.SystemWorker.new()

Historia
LanzamientoModificaciones
19 R4Añadidos

4D.SystemWorker.new ( commandLine : Text { ; options : Object } ) : 4D.SystemWorker

ParámetrosTipoDescripción
commandLineText->Línea de comando a ejecutar
optionsObject->Parámetros worker
result4D.SystemWorker<-Nuevo System worker asíncrono o null si el proceso no se ha iniciado

Descripción

The 4D.SystemWorker.new() function creates and returns a 4D.SystemWorker object that will execute the commandLine you passed as parameter to launch an external process.

El objeto system worker devuelto puede utilizarse para enviar mensajes al worker y obtener los resultados del worker.

If an error occurs during the creation of the proxy object, the function returns a null object and an error is thrown.

In the commandLine parameter, pass the full path of the application's file to be executed (posix syntax), as well as any required arguments, if necessary. If you pass only the application name, 4D will use the PATH environment variable to locate the executable.

Warning: This function can only launch executable applications; it cannot execute instructions that are part of the shell (command interpreter). For example, under Windows it is not possible to use this command to execute the dir instruction.

Objeto options

In the options parameter, pass an object that can contain the following properties:

PropiedadTipoPor defectoDescripción
onResponseFormulaindefinidoRetrollamada para los mensajes del system worker. Esta retrollamada se llama una vez que se recibe la respuesta completa. Recibe dos objetos como parámetros (ver más abajo)
onDataFormulaindefinidoRetrollamada para los datos del system worker. Esta retrollamada se llama cada vez que el system worker recibe los datos. Recibe dos objetos como parámetros (ver más abajo)
onDataErrorFormulaindefinidoCallback for the external process errors (stderr of the external process). Recibe dos objetos como parámetros (ver más abajo)
onErrorFormulaindefinidoRetrollamada para los errores de ejecución, devueltos por el system worker en caso de condiciones de ejecución inusuales (errores del sistema). Recibe dos objetos como parámetros (ver más abajo)
onTerminateFormulaindefinidoRetrollamada cuando el proceso externo se termina. Recibe dos objetos como parámetros (ver más abajo)
timeoutNumberindefinidoTiempo en segundos antes de que el proceso sea eliminado si aún está activo
dataTypeText"text"Tipo de contenido del cuerpo de la respuesta. Valores posibles: "text" (por defecto), "blob".
encodingText"UTF-8"Only if dataType="text". Codificación del contenido del cuerpo de la respuesta. For the list of available values, see the CONVERT FROM TEXT command description
variablesObjectDefine las variables de entorno personalizadas para el system worker. Syntax: variables.key=value, where key is the variable name and value its value. Los valores se convierten en cadenas de caracters cuando es posible. El valor no puede contener un '='. Si no se define, el system worker hereda del entorno 4D.
currentDirectoryFolderDirectorio de trabajo en el que se ejecuta el proceso
hideWindowBooleantrue(Windows) Ocultar la ventana de la aplicación (si es posible) o la consola Windows

Todas las funciones de retrollamada reciben dos parámetros objeto. Su contenido depende de la retrollamada:

ParámetrosTipoonResponseonDataonDataErroronErroronTerminate
$param1ObjectSystemWorkerSystemWorkerSystemWorkerSystemWorkerSystemWorker
$param2.typeText"response""data""error""error""termination"
$param2.dataText o Blobdatos recibidosdatos de error

Esta es la secuencia de llamadas de retorno:

  1. onData and onDataError are executed one or several times
  2. if called, onError is executed once (stops the system worker processing)
  3. if no error occured, onResponse is executed once
  4. onTerminate is always executed

Valor devuelto

La función devuelve un objeto system worker sobre el que se pueden llamar las funciones y las propiedades de la clase SystemWorker.

Ejemplos en Windows

  1. Para abrir el Bloc de notas y abrir un documento específico:
var $sw : 4D.SystemWorker
var $options : Object
$options:=New object
$options.hideWindow:= False

$sw:=4D.SystemWorker.new ("C:\\WINDOWS\\notepad.exe C:\\Docs\\new folder\\res.txt";$options)
  1. Ejecutar npm install en la consola:
var $folder : 4D.Folder
var $options : Object
var $worker : 4D.SystemWorker

$folder:=Folder(fk database folder)
$options:=New object
$options.currentDirectory:=$folder
$options.hideWindow:=False

$worker:=4D.SystemWorker.new("cmd /c npm install";$options)

  1. Para lanzar la aplicación Microsoft® Word® y abrir un documento específico:
$mydoc:="C:\\Program Files\\Microsoft Office\\Office15\\WINWORD.EXE C:\\Tempo\\output.txt"
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new($mydoc)
  1. Para lanzar un comando con el directorio actual y publicar un mensaje:
var $param : Object
var $sys : 4D.SystemWorker

$param:=New object
$param.currentDirectory:=Folder(fk database folder)
$sys:=4D.SystemWorker.new("git commit -F -";$param)
$sys.postMessage("This is a postMessage")
$sys.closeInput()
  1. Para permitir al usuario abrir un documento externo en Windows:
$docname:=Select document("";"*.*";"Choose the file to open";0)
If(OK=1)
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new("cmd.exe /C start \"\" \""+$docname+"\"")
End if

Ejemplos en macOS

  1. Edit a text file (cat is the macOS command used to edit files). En este ejemplo, se pasa la ruta de acceso completa del comando:

var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new("/bin/cat /folder/myfile.txt")
$sw.wait() //synchronous execution

  1. To launch an independent "graphic" application, it is preferable to use the open system command (in this case, the code has the same effect as double-clicking the application):
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new ("open /Applications/Calculator.app")
  1. Para obtener el contenido de la carpeta "Users" (ls -l es el equivalente en macOS del comando dir en DOS).
var $systemworker : 4D.SystemWorker
var $output : Text
var $errors : Collection

$systemworker:=4D.SystemWorker.new("/bin/ls -l /Users ")
$systemworker.wait(5)
$output:=$systemworker.response
$error:=$systemworker.errors

  1. El mismo comando que el anterior, pero utilizando un ejemplo de clase usuario "Params" para mostrar cómo manejar las funciones de retrollamada:

var $systemworker : 4D.SystemWorker
$systemworker:=4D.SystemWorker.new("/bin/ls -l /Users ";cs.Params.new())


// "Params" class

Class constructor
This.dataType:="text"
This.data:=""
This.dataError:=""

Function onResponse($systemWorker : Object)
This._createFile("onResponse"; $systemWorker.response)

Function onData($systemWorker : Object; $info : Object)
This.data+=$info.data
This._createFile("onData";this.data)

Function onDataError($systemWorker : Object; $info : Object)
This.dataError+=$info.data
This._createFile("onDataError";this.dataError)

Function onTerminate($systemWorker : Object)
var $textBody : Text
$textBody:="Response: "+$systemWorker.response
$textBody+="ResponseError: "+$systemWorker.responseError
This._createFile("onTerminate"; $textBody)

Function _createFile($title : Text; $textBody : Text)
TEXT TO DOCUMENT(Get 4D folder(Current resources folder)+$title+".txt"; $textBody)

.closeInput()

Historia
LanzamientoModificaciones
19 R4Añadidos

.closeInput()

ParámetrosTipoDescripción
No requiere ningún parámetro

Descripción

The .closeInput() function closes the input stream (stdin) of the external process.

When the executable waits for all data to be received through postMessage(), .closeInput() is useful to indicate to the executable that data sending is finished and that it can proceed.

Ejemplo

// Create some data to gzip
var $input;$output : Blob
var $gzip : Text
TEXT TO BLOB("Hello, World!";$input)
$gzip:="\"C:\\Program Files (x86)\\GnuWin32\\bin\\gzip.exe\" "

// Create an asynchronous system worker
var $worker : 4D.SystemWorker
$worker:= 4D.SystemWorker.new($gzip;New object("dataType";"blob"))

// Send the compressed file on stdin.
$worker.postMessage($input)
// Note that we call closeInput() to indicate we're done.
// gzip (and most program waiting data from stdin) will wait for more data until the input is explicitely closed.
$worker.closeInput()
$worker.wait()

$output:=$worker.response

.commandLine

.commandLine : Text

Descripción

The .commandLine property contains the command line passed as parameter to the new() function.

Esta propiedad es de solo lectura.

.currentDirectory

.currentDirectory : 4D.Folder

Descripción

The .currentDirectory property contains the working directory in which the external process is executed.

.dataType

.dataType : Text

Descripción

The .dataType property contains the type of the response body content. Valores posibles: "text" o "blob".

Esta propiedad es de solo lectura.

.encoding

.encoding : Text

Descripción

The .encoding property contains the encoding of the response body content. This property is only available if the dataType is "text".

Esta propiedad es de solo lectura.

.errors

.errors : Collection

Descripción

The .errors property contains a collection of 4D errors in case of execution error(s) if any.

Cada elemento de la colección es un objeto con las siguientes propiedades:

PropiedadTipoDescripción
[].errorCodenumberCódigo de error 4D
[].messagetextDescripción del error 4D
[ ].componentSignaturetextFirma del componente interno que ha devuelto el error

If no error occured, .errors is undefined.

.exitCode

.exitCode : Integer

Descripción

The .exitCode property contains the exit code returned by the external process. If the process did not terminate normaly, exitCode is undefined.

Esta propiedad es de solo lectura.

.hideWindow

.hideWindow : Boolean

Descripción

The .hideWindow property can be used to hide the window of the DOS console or the window of the launched executable (Windows only).

This property is read-write.

.pid

.pid : Integer

Descripción

The .pid property contains the process unique identifier of the external process at the system level.

Esta propiedad es de solo lectura.

.postMessage()

.postMessage( message : Text)
.postMessage( messageBLOB : Blob)

ParámetrosTipoDescripción
messageText->Texto a escribir en el flujo de entrada (stdin) del proceso externo
messageBLOBBlob->Bytes escritos en el flujo de entrada

Descripción

The .postMessage() function allows you to write on the input stream (stdin) of the external process. In the message parameter, pass the text to write in stdin.

The .postMessage() function also accepts a Blob type value in messageBLOB to pass in stdin, so that you can post binary data.

You can use the .dataType property of the options object to make response body return Blob values.

.response

.response : Text
.response : Blob

Descripción

The .response property contains the concatenation of all data returned once the request is terminated, i.e. the full message received from the process output.

The type of the message is defined according to the dataType attribute.

Esta propiedad es de solo lectura.

.responseError

.responseError : Text

Descripción

The .responseError property contains the concatenation of all the errors returned, once the request is terminated.

.terminate()

.terminate()

ParámetrosTipoDescripción
No requiere ningún parámetro

Descripción

The .terminate() function forces the SystemWorker to terminate its execution.

Esta función envía la instrucción de terminar y devolver el control al script en ejecución.

.terminated

.terminated : Boolean

Descripción

The .terminated property contains true if the external process is terminated.

Esta propiedad es de solo lectura.

.timeout

.timeout : Integer

Descripción

The .timeout property contains the duration in seconds before the external process will be killed if it is still alive.

Esta propiedad es de solo lectura.

.wait()

Historia
LanzamientoModificaciones

|19 R4|Añadido|

.wait( {timeout : Real} ) : 4D.SystemWorker

ParámetrosTipoDescripción
timeoutReal->Tiempo de espera (en segundos)
Result4D.SystemWorker<-Objeto SystemWorker

Descripción

The .wait() function waits until the end of the SystemWorker execution or the specified timeout.

In timeout, pass a value in seconds. The SystemWorker script will wait for the external process for the amount of time defined in the timeout parameter. If you omit the timeout parameter, the script execution will wait indefinitely.

Actually, .wait() waits until the end of processing of the onTerminate formula, except if the timeout is reached. If timeout is reached, the SystemWorker is not killed.

During a .wait() execution, callback functions are executed, especially callbacks from other events or from other SystemWorker instances. You can exit from a .wait() by calling terminate() from a callback.

Esta función devuelve el objeto SystemWorker.

This function is not necessary if you created the SystemWorker from a 4D worker process.