SystemWorker
System workers allow the 4D code to call any external process (a shell command, PHP, etc.) on the same machine. Os trabalhadores do sistema são chamados assíncronos. Ao utilizar os callbacks, 4D torna possível a comunicação de ambas as maneiras.
The SystemWorker
class is available from the 4D
class store.
Exemplo
// 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")
Resumo
| 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()
História
Release | Mudanças |
---|---|
19 R4 | Adicionado |
4D.SystemWorker.new ( commandLine : Text { ; options : Object } ) : 4D.SystemWorker
Parâmetro | Tipo | Descrição | |
---|---|---|---|
commandLine | Text | -> | Linha de comando a executar |
options | Object | -> | Parâmetros worker |
result | 4D.SystemWorker | <- | Novo System worker assíncrono ou nulo se o processo não for iniciado |
Descrição
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.
O objecto worker do sistema devolvido pode ser utilizado para postar mensagens ao worker e obter a saída do 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:
Propriedade | Tipo | Por padrão | Descrição |
---|---|---|---|
onResponse | Formula | indefinido | Chamada de retorno para mensagens de worker do sistema. Esta chamada de retorno é chamada assim que a resposta completa é recebida. Recebe dois objectos como parâmetros (ver abaixo) |
onData | Formula | indefinido | Chamada de retorno para os dados do worker do sistema. Esta chamada de retorno é chamada cada vez que o worker do sistema recebe dados. Recebe dois objectos como parâmetros (ver abaixo) |
onDataError | Formula | indefinido | Callback for the external process errors (stderr of the external process). Recebe dois objectos como parâmetros (ver abaixo) |
onError | Formula | indefinido | Chamada de retorno para erros de execução, devolvida pelo worker do sistema em caso de condições anormais de tempo de execução (erros de sistema). Recebe dois objectos como parâmetros (ver abaixo) |
onTerminate | Formula | indefinido | Chamada de retorno quando o processo externo é terminado. Recebe dois objectos como parâmetros (ver abaixo) |
timeout | Number | indefinido | Tempo em segundos antes de o processo ser terminado se ainda estiver vivo |
dataType | Text | "text" | Tipo de conteúdo do corpo da resposta. Valores possíveis: "text" (predefinição), "blob". |
encoding | Text | "UTF-8" | Only if dataType="text" . Codificação do conteúdo do corpo da resposta. For the list of available values, see the CONVERT FROM TEXT command description |
variables | Object | Define variáveis de ambiente personalizadas para o system worker. Syntax: variables.key=value , where key is the variable name and value its value. Os valores são convertidos em cordas quando possível. O valor não pode conter um '='. Se não estiver definido, o system worker herda do ambiente 4D. | |
currentDirectory | Folder | Directório de trabalho no qual o processo é executado | |
hideWindow | Parâmetros | true | (Windows) Esconder a janela de aplicação (se possível) ou a consola Windows |
Todas as funções de chamada de retorno recebem dois parâmetros de objectos. O seu conteúdo depende do retorno da chamada:
Parâmetro | Tipo | onResponse | onData | onDataError | onError | onTerminate |
---|---|---|---|---|---|---|
$param1 | Object | SystemWorker | SystemWorker | SystemWorker | SystemWorker | SystemWorker |
$param2.type | Text | "response" | "data" | "error" | "error" | "termination" |
$param2.data | Text ou Blob | dados recebidos | dados de erro |
Aqui está a sequência de chamadas de retorno:
onData
andonDataError
are executed one or several times- if called,
onError
is executed once (stops the system worker processing) - if no error occured,
onResponse
is executed once onTerminate
is always executed
Valor retornado
A função devolve um objecto system worker sobre o qual se pode chamar funções e propriedades da classe SystemWorker.
Exemplos no Windows
- Para abrir o Bloco de Notas e abrir um 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)
- Executar npm instalar na 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)
- Para lançar a aplicação Microsoft® Word® e abrir um 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)
- Para lançar um comando com o diretório atual e publicar uma mensagem:
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()
- Para permitir que o utilizador abra um documento externo no 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
Exemplos em macOS
- Edit a text file (
cat
is the macOS command used to edit files). Neste exemplo, o caminho de acesso completo do comando é passado:
var $sw : 4D.SystemWorker
$sw:=4D.SystemWorker.new("/bin/cat /folder/myfile.txt")
$sw.wait() //synchronous execution
- 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")
- Para obter o conteúdo da pasta "Users" (ls -l é o equivalente em macOS do comando dir em 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
- O mesmo comando que acima, mas usando uma amostra de classe de utilizador "Params" para mostrar como lidar com as funções 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()
História
Release | Mudanças |
---|---|
19 R4 | Adicionado |
.closeInput()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
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.
Exemplo
// 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
Descrição
The .commandLine
property contains the command line passed as parameter to the new()
function.
This property is read-only.
.currentDirectory
.currentDirectory : 4D.Folder
Descrição
The .currentDirectory
property contains the working directory in which the external process is executed.
.dataType
.dataType : Text
Descrição
The .dataType
property contains the type of the response body content. Valores possíveis: "text" ou "blob".
This property is read-only.
.encoding
.encoding : Text
Descrição
The .encoding
property contains the encoding of the response body content. This property is only available if the dataType
is "text".
This property is read-only.
.errors
.errors : Collection
Descrição
The .errors
property contains a collection of 4D errors in case of execution error(s) if any.
Cada elemento da coleção é um objeto com as seguintes propriedades:
Propriedade | Tipo | Descrição |
---|---|---|
[].errorCode | number | Código de erro 4D |
[].message | text | Descrição do erro 4D |
[ ].componentSignature | text | Assinatura da componente interna que devolveu o erro |
If no error occured, .errors
is undefined.
.exitCode
.exitCode : Integer
Descrição
The .exitCode
property contains the exit code returned by the external process. If the process did not terminate normaly, exitCode
is undefined.
This property is read-only.
.hideWindow
.hideWindow : Boolean
Descrição
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
Descrição
The .pid
property contains the process unique identifier of the external process at the system level.
This property is read-only.
.postMessage()
.postMessage( message : Text)
.postMessage( messageBLOB : Blob)
Parâmetro | Tipo | Descrição | |
---|---|---|---|
message | Text | -> | Texto para escrever no fluxo de entrada (stdin) do processo externo |
messageBLOB | Blob | -> | Bytes escritos no fluxo de entrada |
Descrição
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
Descrição
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.
This property is read-only.
.responseError
.responseError : Text
Descrição
The .responseError
property contains the concatenation of all the errors returned, once the request is terminated.
.terminate()
.terminate()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .terminate()
function forces the SystemWorker
to terminate its execution.
Esta função envia a instrução para terminar e devolver o controlo ao guião de execução.
.terminated
.terminated : Boolean
Descrição
The .terminated
property contains true if the external process is terminated.
This property is read-only.
.timeout
.timeout : Integer
Descrição
The .timeout
property contains the duration in seconds before the external process will be killed if it is still alive.
This property is read-only.
.wait()
História
Release | Mudanças |
---|
|19 R4|Adicionado|
.wait( {timeout : Real} ) : 4D.SystemWorker
Parâmetro | Tipo | Descrição | |
---|---|---|---|
timeout | Real | -> | Tempo de espera (em segundos) |
Resultados | 4D.SystemWorker | <- | Objecto SystemWorker |
Descrição
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 função devolve o objecto SystemWorker.
This function is not necessary if you created the
SystemWorker
from a 4D worker process.