luaXroot Wiki


System calls and basic functions

Inter-Process Communications


System calls and basic functions

Lua libraries

Lua includes an interface to call some system functions. The os library.

A useful function is for instance the getenv function allowing you to retrieve environment variables from a Lua script

   os.getenv("ROOTSYS") -- will return the path the the ROOT installation

Lua also includes:

  • a math library with common and useful mathematical functions.
  • a io library to perform classic input/output operations (opening a file, closing a file, reading from a file, writing...)
  • a string library It of course has functions to format a string as the C function printf would do with string.format or function to search for patterns or extract substrings...

The string library has surprising additional functionalities. It can be used to encode and decode binary data using the "string.pack" and "string.unpack" functions (more about this here).

go back to top


luaXroot additions

luaXroot also offers binders to most of these system calls and basic functions.
Below are a list of these functions with a description and their arguments list.

  • Each argument is specified using the following nomenclature: < type, default value if any >
    Examples: , < float, 3.14157 >, < string, "O_RDONLY | O_NONBLOCK" >, ...
  • A [o] in front of an argument means that it's optional.
  • Some functions takes an arguments table. In this case the arguments are enclosed with { ... }. Each argument inside the table has a name that MUST be specified when calling the function. The advantage of arguments tables is that optional arguments can be omitted completely when calling the function, and passed in any order.

SysOpen

({name=< string >, [o] flags=< string, "O_RDONLY | O_NONBLOCK" >, [p] mode=< string, "0666" >})
Return values: int

Returns an integer corresponding to the [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) associated to the opened file.
Takes an arguments table.
You might want to use this function instead of the io.open if you want more controls over how the file is opened (permissions, ...)

  • name: the name of the file
  • flags: define how the file will be opened ("O_RDONLY" for read only, "O_RDWR" for read and write, ...). They have to be given as a string. Bitwise AND and OR operations are possible (e.g. "O_RDONLY | O_NONBLOCK"). See [this page](https://linux.die.net/man/3/open) for the different flags.
  • mode: permission on the file given as a string (default "0666")

go back to top

SysClose

(< int >)
Return values: nil

Closes the file associated to the file descriptor passed as the first argument.

go back to top

SysFtruncate

({fd=< int >, size=< int >})
Return values: nil

Causes the file associated to the file descriptor fd to be truncated to exactly the size specified by size.
It If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
The file offset is not changed.
more information

go back to top

SysRead

({fd=< int >, [o] size=< int >})
Return value: string, int

Read size bytes from the file corresponding to the file descriptor fd. If size is not specified, read all the available data.
It returns the read data as a string, followed by the amount of bytes read.

go back to top

SysWrite

({fd=< int >, data=< string >, [o] size=< int >})
Return values: int

Write size bytes from the string data to the file associated to the file descriptor fd. If size is not specified, it writes all the available data.
It returns the amount of bytes written.

go back to top

SysDup

(< int >)
Return values: int

Creates a copy of the file descriptor given as the first argument using the lowest-numbered unused file descriptor.
It returns that new file descriptor.

go back to top

SysDup2

(< int >, < int >)
Return values: nil

Performs the same operation as SysDup but using the file descriptor provided as second argument instead of the lowest-numbered unused one.

go back to top

MakePipe

( )
Return values: int, int

Creates a pipe between 2 file descriptors and returns them (the first one is the input of the pipe, the second one is the ouput).

go back to top

MakeFifo

({name=< string >, [o] mode=< string, "0777" >})
Return values: nil

Create a FiFo using the name argument.
mode is the permission to use to create the FiFo.

go back to top

SysFtok

({pathname=< string >, [o] id=< int, 90 >})
Return values: int

Generates a key using the pathname argument. This key is used to initiate Semaphores, Messages Queues or Shared Memory Segments.
id is used only if more than 1 key need to be generated using the same file.

go back to top

SysSelect

({[o] read=< table >, [o] write=< table >, [o] exception=< table >})
Return values: table, table, table

Allows to monitor multiple file descriptors simultaneously, and check whether any of these is ready for one of the following operations: read, write and exceptions.
The file descriptors you wish to monitor should be placed in tables and passed in the matching category.
When SysSelect returns, it returns 3 tables/nil values. The first value is either nil (if no file descriptor was ready to be read or if none were being monitored for read operation) or a table containing all the file descriptors ready to be read. The second value return is the same for the write operation and the third is for the exception operation.
For a detailed description of the select C function, click here.

go back to top

SysExec

({file=< string >, args=< table >, [o] env=< table >})
Return values: nil

Execute the process corresponding to the command file with the arguments args. The first argument in the args table must be the command to execute. It is often redundant with the file.
A list of environment variables can be passed in env.
For instance, one could run the echo command inside a Lua script
   SysExec({file="echo", args={"echo", "Hellow World"}}) 
   -- this will display on screen "Hello World" 
   -- and terminate the process

go back to top

SysFork

({fn=< function >, [o] args=< table >, [o] preinit=< function >})
Return values: nil

Fork the process and execute the function fn with the arguments args in the child process.
This can be used to start a new task in the background. Note that this function duplicates the process and does not create a new thread. It's usage is very specific and does not allow further communication with the forked process from the master process. StartNewTask should be the preferred method when one wants to start a new background task.

Example

   local EchoFn = function(message)
      SysExec({file="echo", args={"echo", message}})
   end

   SysFork({fn=EchoFn, args={"Hello World"}})
   -- This command created a clone of the current process. 
   -- The cloned process will execute the command *echo "Hello World"* 
   -- and terminate while the master process whill keep on running.

go back to top

MakeSlaveTerm

({ [o] fontstyle=< string, "Monospace" >, [o] fontsize=< int, 10 >, [o] bgcolor=< string >, [o] fgcolor=< string >, [o] geometry=< string >, [o] title=< string >, [o] label=< string >})
Return values: FileObject

Create a terminal for the user to perform output operations. This can be useful to redirect the log from a process and keep the command interpreter clean.

  • fontstyle: set the style used for the font. This style is a FreeType library pattern.
  • fontsize: set the size of the font.
  • bgcolor: set the background color. See this link for the color names.
  • fgcolor: set the font color. See this link for the color names.
  • title: set the title of the xterm window.
  • label: set the name of the xterm window when minimized.
  • geometry: a string with the format widthxheight+x position+y position. Example: 100x15+300+400

Example

   local EchoFn = function(message)
      SysExec({file="echo", args={"echo", message}})
   end

   SysFork({fn=EchoFn, args={"Hello World"}})
   -- This command created a clone of the current process. 
   -- The cloned process will execute the command *echo "Hello World"* 
   -- and terminate while the master process whill keep on running.

go back to top


Inter-Process Communications

luaXroot provides "raw" binders for the different inter-process communication tools as well as wrapper and helper functions to manipulate them

Messages Queues

MsgGet

({key=< int >, [o] flags=< string, "IPC_CREAT | IPC_EXCL | 0666" >})
Return values: int

Create or retrieve a message queue using the key provided by the argument key and returns its ID. The fact that the message queue is created or not depends on the flags specified. See this link for a list of the possible flags.

go back to top

MsgSnd

({msgid=< int >, data=< table >, [o] mtype=< int, 0 >, [o] flags=< string >})
Return values: nil

Send the message contained in the table *data* to the message queue identified by msgid.
The data argument is a table containing itself 2 subtables:

  • data={format=< table >, values=< table >}
  • format is the string identifier of the elements inside the message.
  • values are the values of the elements inside the message.

Example

   -- [... Some code before generating a key msgkey ... ]

   mid = MsgGet({key=msgkey})

   local message_vals = { 3.14157, "Hello World", true, -8 }
   local message_format = { "float", "string", "bool", "int" }

   local message = { format=message_format , values=message_vals }

   MsgSnd( { msgid=mid, data=message } )

For an explanation about mtype and flags (optionnal arguments) see this link.

go back to top

MsgRcv

({msgid=< int >, format=< table >, [o] mtype=< int, 0 >, [o] flags=< string >})
Return values: table, bool

Receive the message in the message queue identified by msgid. It uses the format table to determine how to read the message, similarly to the MsgSnd function.

For an explanation about mtype and flags (optionnal arguments) see this link.

go back to top

MsgCtl

({msgid=< int >, cmd=< int >})
Return values: nil OR table (depending on cmd argument)

Perform the operation identified by cmd on the message queue identified by msgid.
The supported operations are:

  • IPC_STAT: get statistics about the message queue
  • IPC_RMID: mark the message queue for deletion

These operations are described here.

go back to top

Helpers and Wrappers

Most of these functions are registered in the global table mgsq

PrintMessagesQueuesHelp

( )
Return values: nil

Display help on creating or getting a message queue.

go back to top

msgq.ListActiveMsgqs

( )
Return values: nil

Print a list of the active messages queues and provide statistics.

go back to top

MsgqObject

A Lua Class used to manipulate more easily messages queues.

Members

  • path: path to the message queue file (if any).
  • fd: file descriptor of the message queue file (if any).
  • key: key used to open the message queue.
  • id: identifier of the message queue.
  • size: size in bytes of the messages sent and received.
  • owner: whether or not the MsgqObject is the owner of the message queue.
  • last_msg: last message received.

Methods

  • Receive(< table >, < int >, < string >) : Receives a message and stores it in member last_msg
    • argument 1 as the format table
    • argument 2 as mtype
    • argument 3 as flags
    • Returns the message read in a table
  • Send(< table >, < table >, < int >, < string >) : Sends a message
  • GetLast() : Returns the last message received in a table

go back to top

msgq.CreateMsgq

( path=< string >, flags=< string, "recreate" >)
( key=< int >, flags=< string, "recreate" >)
Return values: MsgqObject

Creates a messages queue using either a path to a file on disk or directly a key.
The flags control how the messages queue will be created and can be

  • open: the messages queue will be opened only if it already exists
  • protected: the messages queue will be created only if it doesn't already exists. If it already exists the function fails.
  • recreate: the messages queue will be created. If it already exists, it deletes it first.

go back to top

msgq.GetMsgq

( path=< string >, [o] flags=< string, "recreate" >)

( key=< int >, [o] flags=< string, "recreate" >)
Return values: MsgqObject

Gets a messages queue using either a path to a file on disk or directly a key.
The flags control how the messages queue will be created and can be

  • open: the messages queue will be opened only if it already exists
  • protected: the messages queue will be created only if it doesn't already exists. If it already exists the function fails.
  • recreate: the messages queue will be created. If it already exists, it deletes it first.

go back to top


Semaphores

SemGet

({key=< int >, [o] nsem=< int, 0 >, [o] flags=< string, "IPC_CREAT | IPC_EXCL | 0666" >})
Return values: int

Get the Semaphores set associated with key and returns its id.
flags describe how to get that Semaphores set (see this link for the different flags)

go back to top

SemCtl

({semid=< int >, [o] semnum=< int >, cmd=< int >, [o] val=< int or table >})
Return values: nil OR int OR table (depending on cmd argument)

Perform the operation identified by cmd on the semaphores set identified by semid.
The supported operations are:

  • SETVAL: in this case val is required to be an int. Set val as the value for semaphore number semnum in the semaphores set indentified by semid.
  • SETALL: in this case val is required to ba a table. Set the values of the semaphores in the set identified by semid using the values contained in the table val.
  • GETVAL: Returns the current value of semaphore number semnum from the set identified by semid
  • GETALL: Returns the values (in a table) of all the semaphores in the set identified by semid
  • GETNCNT: Returns the number of processes waiting for an increase of the value of the semaphore number semnum in the set identified by semid
  • GETZCNT: Returns the number of processes waiting for the value of the semaphore number semnum, in the set identified by semid, to become zero
  • IPC_STAT: get statistics about the semaphores set and returns them in a table
  • IPC_RMID: mark the semaphores set for deletion

Example:

	 [ ... Assuming a key skey has been generated for a semaphore set containing 3 semaphores ... ]
	 
	 SemCtl({semid=sid, semnum=2, cmd=SETVAL, val=8})
	 -- After this operation, the semaphore number 2 in the set sid is set to 8 
	 
	local sem_vals = SemCtl({semid=sid, cmd=GETALL})
	 -- After this operation, sem_vals is a table containing the values fo the 3 semaphores in the set sid 

These operations are described here.

go back to top

SemOp

({semid=< int >, semnum=< table >, sop=< table >})
Return values: nil

Perform the operations contained in the table sop to the corresponding semaphores (given in the table semnum) in the set identified by semid.

Example:

	 [ ... Assuming an id sid has been obtained for a semaphore set containing 3 semaphores ... ]
	 
	 SemOp({semid=sid, semnum={1, 3}, sop={-2, 4}})
	 -- After this operation, the semaphore number 1 is decreased by 2, 
	 --                       the semaphore number 2 is untouched 
	 --                       and the semaphore number 3 is increased by 4

go back to top

Helpers and Wrappers

Most of these functions are registered in the global table sem

PrintSemaphoresHelp

( )
Return values: nil

Display help on creating or getting a semaphores set.

go back to top

msgq.ListActiveSemaphores

( )
Return values: nil

Print a list of the active semaphores sets and provide statistics.

go back to top

SemaphoreObject

A Lua Class used to manipulate more easily semaphores sets.

Members

  • path: path to the semaphores set file (if any).
  • fd: file descriptor of the semaphores set file (if any).
  • key: key used to open the semaphores set.
  • id: id of the semaphores set.
  • nsem: how many semaphores in the set.
  • owner: whether or not the SemaphoreObject is the owner of the set.

Methods

  • SetValue(< int >, < int >) : Sets the value of a semaphore
    • argument 1 is the semaphore number
    • argument 2 is the new value
  • SetAllValue(< table >) : Sets all the values in the set using the table passed as an argument
  • GetValue(< int >) : Gets the value of the semaphore number given by the argument of the function
  • GetAllValue() : Gets the values of all the semaphores in the set and returns it as a table
  • Operate(< table >, < table >) : Operates on the semaphores
    • argument 1 is a table containing the semaphores numbers on which the function will operate
    • argument 2 is a table with the operations to perform

go back to top

sem.CreateSemSet

( path=< string >, nsem=< int >, [o] flags=< string, "recreate" >)

( key=< int >, nsem=< int >, [o] flags=< string, "recreate" >)
Return values: SemaphoreObject

Creates a semaphores set using either a path to a file on disk or directly a key.
The flags control how the semaphores set will be created and can be

  • open: the semaphores set will be opened only if it already exists
  • protected: the semaphores set will be created only if it doesn't already exists. If it already exists the function fails.
  • recreate: the semaphores set will be created. If it already exists, it deletes it first.

go back to top

sem.GetSemSet

( path=< string >)

( key=< int >)
Return values: SemaphoreObject

Gets a semaphores set using either a path to a file on disk or directly a key.

go back to top


Shared Memory Segments

ShmGet

({key=< int >, size=< int >, [o] flags=< string, "IPC_CREAT | IPC_EXCL | 0666" >})
Return values: int

Get the Shared Memory Segment associated to key and returns its id.
flags describe how to get that Shared Memory Segment (see this link for the different flags)

go back to top

ShmAt

({shmid=< int >, [o] buffer=< userdata >, [o] flags=< string, "IPC_CREAT | IPC_EXCL | 0666" >})
Return values: nil

Assign an address to the shared memory segment. Attach buffer to the shared memory segment identified by shmid if specified.
flags are described here.

Example:

	 -- [ ... assuming we have a shared memory segment with id shid ... ]
	 
	 local buf = int()
	 
	 ShmAt({shmid=shid, buffer=buf})
	 
	 buf:Get() -- this will get whatever is the current integer value at the beginning of the shared memory segment

go back to top

ShmCtl

({shmid=< int >, cmd=< int >})
Return values: nil OR table (depending on cmd argument)

Perform the operation identified by cmd on the shared memory segment identified by shmid.
The supported operations are:

  • IPC_STAT: get statistics about the shared memory segment and returns them in a table
  • IPC_RMID: mark the shared memory segment set for deletion

These operations are described here.

go back to top

ShmDt

(< int >)
Return values: nil

Detach the shared memory segment identified by shmid.

go back to top

AssignShm

({shmid = < int >, buffer=< userdata >, [o] offset=< int >})
Return values: nil

Assign buffer to the shared memory segment identified by shmid. If offset is specified, the buffer is attached at the beginning of the shareed memory segment + offset.

Example:

	 -- [ ... assuming we have a shared memory segment with id shid ... ]
	 
	 ShmAt({shmid=shid}) -- we assign an address to the shared memory segment
	 
	 local buf = float() -- we create a userdata of type float
	 
	 AssignShm({shmid=shid, buffer=buf, offset=6})
	 
	 buf:Get() -- this will get whatever is the current float value at the beginning of the shared memory segment + 6 bytes

go back to top

ShmSetMem

({shmid = < int >, input=< table >, format=< table >})
Return values: nil

Set the memory block assigned to the shared memory segment identified by shmid using the tables input and format

Example:

	 -- [ ... assuming we have an assigned shared memory segment with id shid ... ]
	 	 
	 local setblock = { 5.6, true, 9, "Hello World" }
	 local fmt_tbl = { "float", "bool", "int", "string" }
	 
	 ShmSetMem({shmid=shid, input=setblock, format=fmt_tbl})
	 -- The shared memory segment now contains the following
	 --  address [ 0 -> 3 ] [  4 ] [ 5 -> 8 ] [    9 -> 19    ] 
	 --          [   5.6  ] [true] [    9   ] [ "Hello World" ]

go back to top

ShmGetMem

({shmid = < int >, format=< table >})
Return values: table

Get the memory block assigned to the shared memory segment identified by shmid using the tables format

Example:

	 -- assuming we have an assigned shared memory segment with id shid
	 -- and the shared memory segment currently contains the following
	 --  address [ 0 -> 3 ] [  4 ] [ 5 -> 8 ] [    9 -> 19    ] 
	 --          [   5.6  ] [true] [    9   ] [ "Hello World" ]
	 	 
	 local fmt_tbl = { "float", "bool", "int", "string" }
	 
	 local output = ShmGetMem({shmid=shid, format=fmt_tbl})
	 -- output contains { 5.6, true, 9, "Hello World"}

go back to top

ShmRawRead

({shmid = < int >, size=< int >, [o] offset=< int >})
Return values: string

Read size bytes from the shared memory segment identified by shmid. If offset is specified, it will read from the beginning of the memory block + offset

go back to top

Helpers and Wrappers

Most of these functions are registered in the global table sem

PrintSharedMemoryHelp

( )
Return values: nil

Display help on creating or getting shared memory segments.

go back to top

shmem.ListActiveShMem

( )
Return values: nil

Print a list of the active shared memory segments and provide statistics.

go back to top

ShMemObject

A Lua Class used to manipulate more easily shared memory segments.

Members

  • path: path to the shared memory segment file (if any).
  • fd: file descriptor of the shared memory segment (if any).
  • key: key used to open the shared memory segment.
  • id: id of the shared memory segment.
  • size: size of the shared memory segment.
  • buffer: buffer attached to the shared memory segment (if any).
  • struct: table giving the structure of the shared memory segment (if any).
  • current_offset: current position in the shared memory segment.
  • owner: whether or not the ShMemObject is the owner of the shared memory segment.

Methods

  • RawRead(< int >, < int >) : Performs a ShmRawRead on the shared memory segment.
    • argument 1 is the amount of bytes to read.
    • argument 2 is the offset. If omitted, the default value is 0.
  • AutoGet( ) : Automatically performs a readout of the shared memory and returns the result. If no struct member has been set it simply gets the value of buffer. Otherwise it uses a call to ShmGetMem.
  • AutoSet(< same type as buffer OR table >) : Automatically select how to set values in the shared memory. If no struct member has been set it simply sets the value of buffer. Otherwise it uses a call to ShmSetMem.
  • GetStepSize() : Returns the size of the type currently used as a buffer (or struct if one has been set).
  • SetAddress(< userdata >, < int, 0 >) : Set the member buffer using the first argument.
    • argument 1 is a userdata that will be used as a buffer to read the shared memory
    • argument 2 is the offset. The buffer will be assigned to the beginning of the shared memory + offset
  • Read(< int >) : Reads the shared memory at the position given by the argument. That position is the value of the argument * size of the buffer (or equivalent struct if set).
  • SetValue(< table >, < int >) : Operates on the semaphores
    • argument 1 is a table containing the values to set (see this part for more details)
    • argument 2 is the position (value of the argument * size of buffer or struct) where these values should be set.
  • SetStructure(< table >) : A format table that is assign to the member struct.
  • SetOffset(< int >) : Set the current position in the shared memory segment and assign this offset value to current_offset.
  • Advance(< int >) : Shift the address of the buffer by the value passed as an argument. The actual shift is the value of the argument * size of the buffer (or equivalent struct if set).
  • Next(< table >, < table >) : Shifts the buffer forward for an amount of bytes equal to the size of the buffer
  • Previous(< table >, < table >) : Shifts the buffer backward for an amount of bytes equal to the size of the buffer

go back to top

shmem.CreateShMem

( path=< string >, buffer=< userdata >, [o] flags=< string, "recreate" >)

( path=< string >, size=< int >, [o] flags=< string, "recreate" >)

( key=< int >, buffer=< userdata >, [o] flags=< string, "recreate" >)

( key=< int >, size=< int >, [o] flags=< string, "recreate" >)
Return values: ShMemObject

Creates a shared memory segment using either a path to a file on disk or directly a key.
The second argument can either be the size of the shared memory segment in bytes (a buffer can be attached to it later using ShMemObject:SetAddress or a data structure set using ShMemObject:SetStructure) or directly a buffer (which must be a userdata).
The flags control how the shared memory segment will be created and can be

  • open: the semaphores set will be opened only if it already exists
  • protected: the semaphores set will be created only if it doesn't already exists. If it already exists the function fails.
  • recreate: the semaphores set will be created. If it already exists, it deletes it first.

go back to top

shmem.GetShMem

( path=< string >, buffer=< userdata >, [o] flags=< string, "recreate" >)

( path=< string >, size=< int >, [o] flags=< string, "recreate" >)

( key=< int >, buffer=< userdata >, [o] flags=< string, "recreate" >)

( key=< int >, size=< int >, [o] flags=< string, "recreate" >)
Return values: ShMemObject

Same as but won't create or set up the shared memory segment if it doesn't already exists.

go back to top


Memory Mapped Files

go back to top


Sockets

go back to top