Aller au contenu principal
Version: 20 R5 BETA

SystemWorker

System workers allow the 4D code to call any external process (a shell command, PHP, etc.) on the same machine. Les System workers sont appelés de manière asynchrone. En utilisant des callbacks, 4D permet de communiquer dans les deux sens.

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

Exemple

    // 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")

Sommaire

| 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()

Historique
ReleaseModifications
19 R4Ajout

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

ParamètresTypeDescription
commandLineText->Ligne de commande à exécuter
optionsObject->Paramètres du worker
result4D.SystemWorker<-Nouveau System worker asynchrone ou null si le process n'a pas démarré

Description

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.

L'objet system worker retourné peut être utilisé pour envoyer des messages au worker et obtenir les résultats du 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.

options Object

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

PropriétéTypePar défautDescription
onResponseFormulaundefinedCallback pour les messages du system worker. Ce callback est appelé une fois que la réponse complète est reçue. Elle reçoit deux objets en paramètres (voir ci-dessous)
onDataFormulaundefinedCallback pour les données du system worker. Ce callback est appelé chaque fois que le system worker reçoit des données. Elle reçoit deux objets en paramètres (voir ci-dessous)
onDataErrorFormulaundefinedCallback for the external process errors (stderr of the external process). Elle reçoit deux objets en paramètres (voir ci-dessous)
onErrorFormulaundefinedCallback pour les erreurs d'exécution, renvoyées par le system worker en cas de conditions d'exécution inhabituelles (erreurs système). Elle reçoit deux objets en paramètres (voir ci-dessous)
onTerminateFormulaundefinedCallback lorsque le process externe est terminé. Elle reçoit deux objets en paramètres (voir ci-dessous)
timeoutNumberundefinedDélai en secondes avant que le process soit tué s'il est toujours actif
dataTypeText"text"Type de contenu du corps de la réponse. Valeurs possibles : "text" (par défaut), "blob".
encodingText"UTF-8"Only if dataType="text". Encodage du contenu du corps de la réponse. For the list of available values, see the CONVERT FROM TEXT command description
variablesObjectDéfinit des variables d'environnement personnalisées pour le system worker. Syntax: variables.key=value, where key is the variable name and value its value. Les valeurs sont converties en chaînes de caractères lorsque cela est possible. La valeur ne peut pas contenir un '='. S'il n'est pas défini, le system worker hérite de l'environnement 4D.
currentDirectoryFolderRépertoire de travail dans lequel le process est exécuté
hideWindowBooleanvrai(Windows) Masquer la fenêtre de l'application (si possible) ou la console Windows

Toutes les fonctions de callback reçoivent deux paramètres objet. Leur contenu dépend du callback :

ParamètresTypeonResponseonDataonDataErroronErroronTerminate
$param1ObjectSystemWorkerSystemWorkerSystemWorkerSystemWorkerSystemWorker
$param2.typeText"response""data""error""error""termination"
$param2.dataText ou Blobdonnées reçuesdonnées d'erreur

Voici la séquence des appels de callbacks :

  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

Valeur retournée

La fonction renvoie un objet system worker sur lequel vous pouvez appeler les fonctions et les propriétés de la classe SystemWorker.

Exemples sous Windows

  1. Pour ouvrir le Bloc-notes et ouvrir un document spécifique :
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. Exécuter npm install dans la console :
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. Pour lancer l'application Microsoft® Word® et ouvrir un document spécifique :
$mydoc:="C:\\Program Files\\Microsoft Office\\Office15\\WINWORD.EXE C:\\Tempo\\output.txt"
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new($mydoc)
  1. Pour lancer une commande avec le répertoire courant et poster un message :
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. Pour permettre à l'utilisateur d'ouvrir un document externe sous Windows :
$docname:=Select document(" ; "*.*" ; "Choisissez le fichier à ouvrir";0)
If(OK=1)
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new("cmd.exe /C start \"\" \""$docname"\"")
End if

Exemples sous macOS

  1. Edit a text file (cat is the macOS command used to edit files). Dans cet exemple, le chemin d'accès complet de la commande est transmis :

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. Pour obtenir le contenu du dossier "Users" (ls -l est l'équivalent sous macOS de la commande dir sous 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. Même commande que ci-dessus, mais en utilisant un exemple de classe utilisateur "Params" pour montrer comment gérer les fonctions de callback :

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()

Historique
ReleaseModifications
19 R4Ajout

.closeInput()

ParamètresTypeDescription
Ne requiert aucun paramètre

Description

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.

Exemple

// 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

Description

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

Cette propriété est en lecture seule.

.currentDirectory

.currentDirectory : 4D.Folder

Description

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

.dataType

.dataType : Text

Description

The .dataType property contains the type of the response body content. Valeurs possibles : "text" ou "blob".

Cette propriété est en lecture seule.

.encoding

.encoding : Text

Description

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

Cette propriété est en lecture seule.

.errors

.errors : Collection

Description

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

Chaque élément de la collection est un objet avec les propriétés suivantes :

PropriétéTypeDescription
[].errorCodenumberCode d'erreur 4D
[].messagetextDescription de l'erreur 4D
[ ].componentSignaturetextSignature du composant interne qui a retourné l'erreur

If no error occured, .errors is undefined.

.exitCode

.exitCode : Integer

Description

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

Cette propriété est en lecture seule.

.hideWindow

.hideWindow : Boolean

Description

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

Description

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

Cette propriété est en lecture seule.

.postMessage()

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

ParamètresTypeDescription
messageText->Texte à écrire dans le flux d'entrée (stdin) du process externe
messageBLOBBlob->Octets écrits dans le flux d'entrée

Description

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

Description

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.

Cette propriété est en lecture seule.

.responseError

.responseError : Text

Description

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

.terminate()

.terminate()

ParamètresTypeDescription
Ne requiert aucun paramètre

Description

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

Cette fonction envoie l'instruction de terminer et de redonner le contrôle au script en cours d'exécution.

.terminated

.terminated : Boolean

Description

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

Cette propriété est en lecture seule.

.timeout

.timeout : Integer

Description

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

Cette propriété est en lecture seule.

.wait()

Historique
ReleaseModifications

|19 R4|Ajouté|

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

ParamètresTypeDescription
timeoutReal->Temps d'attente (en secondes)
Résultat4D.SystemWorker<-Objet SystemWorker

Description

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.

Cette fonction renvoie l'objet SystemWorker.

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