Send Feedback
Skip to content

13. Commands and System Variables

In previous versions of this text we attempted to be comprehensive in our coverage of commands and system variables. The main reason was that there was no other place to find their entirety with a consistent presentation. In this version we shall not be comprehensive.

First, there are significantly more commands and system variables, many of which are more appropriate for advanced q programmers with complex applications and are beyond the scope of this tutorial.

More importantly, the KX site now documents them comprehensively, so we have little to add. Here we augment the content from the previous version with the more significant additions since its publication. We refer the reader to the KX site for complete coverage.

13.1 Command Format

Commands control aspects of the q run-time environment. A command is of the form

\*cmd* [*parms*]
where cmd is the command name which is usually one but sometimes two character(s) in length and parms is an optional list of parameters. The parameters are separated from the command name by whitespace---no longer restricted to a single blank as in earlier versions. Case is significant in the command name.

Optional parameters

  • A command whose optional parameter sets an environmental value will display the current value when the parameter is omitted.
  • A command whose parameter refers to a namespace applies to the current namespace if the parameter is omitted.

Important

Don't even think of executing a command programmatically by placing it in a string as an argument to value. It exposes your system to all manner of attacks! Instead use the built-in system that checks for a valid command. Note that system obviates the initial backslash.

q)system "p 5042"

Note

In the following we use the phrase "in the optional ns" as shorthand for "in namespace ns if present or in the current namespace if not." Similarly we use the phrase "displays or sets to" as shorthand for "displays the current value of, if no parameter, or uses the supplied parameter to set the current value to."

13.1.1 \a tables

The command \a [ns] returns a sorted list of symbolic names of all tables in the optional namespace ns. In a fresh q session,

q)\a
`symbol$()
q)t2:t1:([] c1:`a`b`c; c2:10 20 30)
q)\a
`s#`t1`t2
q).jab.t:t1
q)\a .jab
,`t

13.1.2 \b views/aliases

The command \b [ns] (lower case) returns a sorted list of the symbolic names of the views (a.k.a. aliases, dependencies) in the optional ns. In a fresh q session,

q)a:42
q)b::a+1
q)c::b*b
q)\b
`s#`b`c

See 13.3.3 for the related .z.b.

13.1.3 \B pending views

The command \B [ns] (upper case) returns a sorted list of the symbolic names of the views (a.k.a. aliases, dependencies) in the optional ns that are stale – i.e., there is a pending update due to referent(s) changing that will be realized on the next reference. In a fresh q session,

q)x:42
q)a::x+1
q)\B
,`a
q)a
43
q)\B
`symbol$()

See 13.3.3 for the related .z.b.

13.1.4 \c console

The command \c [h w] (lower case) displays or sets the pair of integer height and width of the q virtual console display. As of q4.1 the default is of the size of the command-shell window, which on the author's MacBook is 24 77i. The values are coerced to the range 10..2000. In a fresh q session, we can explain the width as counting the double quote, the .. and the invisible newline. But the author is at a loss for the height display.

q)\c 10 10
q)12 12#"0123456789AB"
"012345.."
"012345.."
"012345.."
"012345.."
"012345.."
"012345.."
"012345.."
..
q)

13.1.5 \C HTTP console

The command \C [h w] (upper case) displays or sets the pair of integer height and width of the q virtual display for HTTP requests. The default on the author's laptop is 36 2000i. In a fresh q session, open port 5042 and point the browser to

<http://localhost:5042?til> each 1+til 10

The browser page will display:

,0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
Now issue the q command,

q)\C 10 20

and refresh the browser page. The page will now display the following which is indeed 10 by 10.

,0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 ..
0 1 2 3 ..
0 1 2 3 ..
0 1 2 3 ..
0 1 2 3 ..

13.1.6 \cd OS directory

The command \cd [path] is issued to the OS. To display the current directory, invoke \cd with no argument.

q)\cd
"/Users/jaborror"

To change the current working directory, issue \cd with the path of the desired directory. The \cd command creates the directory if it does not exist. For example, the directory /Users/jaborror/nuba is initially empty.

q)\cd
"/Users/jaborror"
q)\ls nuba
ls: nuba: No such file or directory
'os
[0] \ls nuba
    ^
q)\cd nuba
q)\cd
"/Users/jaborror/nuba"

13.1.7 \d current namespace

The command \d [ns] displays or sets the current namespace (a.k.a. context in early versions of q and directory in versions of k). In a fresh q session this defaults to root. If the specified namespace does not exist, it will be created. Observe that thw current namespace is displayed as part of the q) prompt.

q)\d
`.
q)\d .jab
q.jab)a:42
q.jab)\d .
q)

Important

See our recommendations against using \d in 12.7.

13.1.8 \e error trap

The command \e [0|1|2] (lower case) displays or sets the behavior of a q process when an exception occurs during processing a client (i.e., remote) IPC request. In a fresh q session the default is 0 meaning that when an exception occurs the stack of the failing function is cleared and execution continues.

In a development or testing scenario you can set this value to 1 to enable the familiar single line of the stack trace from the interactive console. Or you can set it to 2 to dump the stack to stderr for un-trapped errors.

13.1.9 \E TLS server mode

The command \E [0|1|2] (upper case) displays TLS server mode as an int: 0 plain; 1 plain and TLS; 2 TLS only.

13.1.10 \f functions

The command \f [ns] displays a sorted list of symbolic names of functions in the optional ns. In a fresh q session,

q)\f
`symbol$()
q)g:{x+1}
q)f:{x*x}
q)\f
`f`g
q).jab.f:{exp x}
q)\f .jab
,`f

13.1.11 \g garbage collection

The command \g [mode] displays or sets the behavior of the garbage collector. The default mode is 0 (deferred). Setting the garbage-collection mode will automatically call .Q.gc[] after setting the provided value. Following is the description of garbage collection from the KX Documentation website. Please go there for details and examples.

Q manages its own thread-local heap. Objects in q use reference counting. As soon as there are no references to an object, its memory is eligible to be returned to the heap. The two modes are:

0 (deferred)

Returns memory to the thread-local heap. Will subsequently return memory to the OS when either .Q.gc[] is called or an allocation fails, hence has a performance advantage, but can be more difficult to dimension or manage memory requirements.

1 (immediate)

As memory is returned to the thread-local heap, if the object is ≥64MB then the memory is returned to the OS instead. This has an associated performance overhead. As per deferred mode, memory used by the heap may be subsequently returned to the OS when either .Q.gc[] is called or an allocation fails.

When q is denied additional address space from the OS, it invokes .Q.gc[] and retries the request to the OS. If the subsequent attempt fails, the request exits with 'wsfull.

13.1.12 \l load

The command \l nm loads a q resource from persistent storage – here "load" is used in a generic sense. The nm parameter can be a directory or a file. Loosely speaking, the rules for loading are,

  • When something is recognized as a q resource, the loading routine makes that resource available in the workspace.
  • When something is not a recognized q resource, it fails.

The loading process recognizes two types of files:

  • A file can be a q (or k) script, which is executed as if the individual lines were entered from the console.
  • A file can be a serialized q entity – e.g., the sym file for a splayed or partitioned table. In this case, the entity is deserialized into memory into a variable named nm.

The situation for a directory is more involved.

  • The directory of a splayed table is mapped into memory with the name of the directory as the variable nm. None of the actual table data is actually loaded into memory at this time.
  • For a directory nm that is the value of one of the permitted partition types, the most recent partition directory (i.e., the one with highest value) is inspected for splayed directories and each such directory is mapped into memory as a virtual table with the name of the splayed directory.
  • The root of a kdb+ database can contain: serialized q entities (e.g., the sym file), scripts (e.g., a start-up script), splayed table directories, partition directories or a par.txt file. In this case, the loading routine recursively "does" each entity that it finds, as outlined above. Scripts are executed last.

For example, to load the distribution script sp.q from the mypath directory under QHOME,

q)\l mypath/sp.q

to map a database whose root is mypath/db,

q)\l mypath/db

When a directory is mapped with \l, the current working directory in the OS is set to that directory. This allows relative paths to subordinate items in the database and also helps to avoid wayward operations.

Note

See 14.5.8 entries .Q.lo and .Q.ld for variations of the loader.

Once you have mapped a database into memory, you can issue the command \l . to remap the data only – i.e., without executing any script(s) in the root.

Dollars for Donuts: If a file or directory under the path being loaded has a dollar-sign suffix then it is ignored. e.g. db/tickdata/myfile$ and db/tickdata/mydir$ would be ignored on \l . provided db/tickdata is the current directory. This is useful, for example, to bypass symlinks that point outside the root, which can be subsequently picked up in par.txt.

13.1.13 \o GMT offset

The command \o [n] displays or sets to the int n the offset from GMT for q date/time values in the current session. When the absolute value of n is strictly less than 24 it is interpreted as hours; if it is 24 or greater it is interpreted as minutes.

In a fresh q session, the value is 0Ni, meaning that the underlying OS time zone offset is used.

q)\o / using OS time zone
0Ni
q).z.t / GMT
11:33:08.088
q).z.T / I am in NY that is on Daylight Stupid Time
07:33:10.919
q)\o -10 / fantasy life in Hawaii that doesn't do DST
q).z.T / life is good
01:33:36.336

See 13.2.8 for the related command line parameter -o.

13.1.14 \p listening port

The command \p [port] (lower case) displays or sets the port on which the q process listens. In a fresh q session the value is 0i, meaning that no port is open and connection attempts are rejected. To close the open port, use 0i as port. In a fresh q session,

q)\p 
0i 
q)\p 5042 
q)\p 
5042i 
q)\p 0 
When you issue the \p command, q attempts to open the port but the security settings of your machine must allow it.

Note

You can set the port to 0W to choose a port that is guaranteed to be available.

As of q4,1 a port range can be specified in place of a port number. The range of ports specified as 'pbegin/pend' is inclusive and tried in a random order.

q)\p 80/85 
q)\p 
84i 

Important

Once you open a port, that q session is by default wide open to all connections, including to HTTP traffic. We strongly recommend that you implement appropriate security around any process with an open port in a production environment.

Tip

To stop the q process from listening on any port issue \p 0.

In q4.1 there is significantly expanded functionality available for a listening q process. See the "Listening Port" topic on the KX site for details.

See 13.2.9 for the related command line parameter -p.

13.1.15 Display Precision (\P)

The command \P [precision] (upper case) displays or sets the display precision for floating point numbers – i.e., float and real types – to the specified number of digits.

Note

Only the display of the floating point values is affected. The internal representation remains unchanged.

The permissible values are 0-17, with 0 meaning maximum. The default precision is 7, meaning that the display of float or real values is rounded to the seventh significant digit. In a fresh q session,

q)\P
7i
q)1%3
0.3333333
q)2%3
0.6666667
q)\P 0
q)show r:1%3
0.33333333333333331
q)r+r+r
1f
q)0.99999999999999993=r+r+r
1b
q)0=0.99999999999999993-r+r+r
0b

Notice the schmutz in the 17th significant digit. This is part of the dark mystery of binary floating point that is not mentioned in polite company.

You can use the utility functions .Q.f and .Q.fmt for controlled formatting of floating point values as strings.

See 13.2.10 for the related command line parameter -P.

13.1.16 \r replication primary

This command should not be executed manually otherwise it can disrupt replication. It is executed automatically by the replicating process on the primary process, and returns the log file name and log file count.

See 13.2.12 for the related command line parameter -r.

13.1.17 \r rename file

The command \r src dst provides an OS independent (i.e., linux, Windows, MacOS, ..) way to rename the file named src to tgt. It is equivalent to Linux mv. It will not move files across disks on Windows.

13.1.18 \s secondary threads

The command \s [n] displays or sets the number of secondary threads – abbreviated in this text to "secondaries" – available for concurrent processing. Since v3.5 secondaries can be adjusted dynamically up to the maximum specified at q startup; if none were specified then \s is display only. A negative n indicates processes should be used instead of threads. A value of 0N displays the max secondaries specified at startup.

No -s specified on startup.

jaborror@Jeffrys-MacBook-Pro ~ % rlwrap q/m64/q
q)\s 4
'enable secondary threads via cmd line -s only
Max secondaries specified as 8 on startup.
jaborror@Jeffrys-MacBook-Pro ~ % rlwrap q/m64/q -s 8
q)\s
8i
q)\s 0N
8i
q)\s 4
q)\s
4i
q)\s 0N
8i

13.1.19 \S seed

The command \S [0N|n] (upper case) displays or sets the initial seed for pseudo-random number generation. If the parameters is omitted it displays the last value to which the random seed was initialized. The parameter 0N displays the current value of the seed. An integer causes the seed to be initialized to that value. This is useful for obtaining repeatable results from randomized testing. The default value is -314159.

Note

The 0N case is a GUID that can be used as a parameter instead of a number.

In a simple q session without secondaries, the behavior is simple. Resetting the seed to a known value allows the pseudo-random values to be reproduced. Observe the digits of the default seed.

q)\S
-314159i
q)-5?10
8 2 4 1 6
q)-5?10
5 0 9 8 1
q)\S -314159i / reset to initial seed and they are back
q)-5?10
8 2 4 1 6
q)sd:system "s 0N"
q)-5?10
8 2 4 1 6 / note these values
q)-5?10
5 0 9 8 1
q)system "s ", string sd
q)-5?10
8 6 4 7 9

See the KX Documentation website for details on how random number generation works in the multi-threaded case.

13.1.20 \t timer

The command \t [n|expr|:n expr] (lower case) has two interpretations, depending on the type of its parameter. If the parameter is omitted, it shows the number of milliseconds between timer ticks; 0 means the timer is off.

When \t [n] is issued with a non-negative integer argument n, it sets the number of milliseconds between timer ticks. For 0i it disables the timer. For n>0 it sets the interval and enables the timer. The default value is 0i.

q).z.ts:{show .z.P}
q)\t 2000
q)2025.07.04D10:54:54.403411000
2025.07.04D10:54:56.404676000
2025.07.04D10:54:58.404498000
2025.07.04D10:55:00.403807000
\t 0
q)

Note

The actual timer tick frequency is determined by the timing granularity supported by the underling operating system. This can be considerably different from a millisecond.

When \t expr is issued with a valid q expression, the expression is evaluated and the execution duration in milliseconds is reported. This can be used to profile code execution when tuning an application.

Some expressions execute so quickly in q that the result is less than the timer granularity. Fortunately \t:n obviates what was formerly the only valid use of do in q – namely, repeating the expression evaluation to raise its execution time above the timer floor.

Tip

There cannot be whitespace between \t and the :.

q)\t sum til 100000
0
q)\t:1000 sum til 100000
34

We conclude that adding the first 100,000 integers once requires approximately .0034 milliseconds. Of course you would never evaluate this exact expression in practice; instead, use the insight of the young Gauss.

13.1.21 \T timeout

The command \T [n] (upper case) displays and sets the number of seconds a remotely initiated execution will run before timing out. The default value is 0, meaning that such execution will not timeout. This is useful to protect against runaway client calls when the q process is acting as a server.

Note

When a query times out it will raise a `'stop error.

See 13.2.15 for the related command line parameter -T.

13.1.22 \ts elapsed time and space

The command \ts expr or \ts:n expr is an enhancement of the version of \t that times an expression. It provides both the time and the number of bytes used in evaluating the expression.

q)\ts log til 100000
2 3144592
You can also specify the number of repetitions. As with \t there cannot be whitespace between \ts and :.

q)\ts:100 log til 100000
71 3145904

13.1.23 \u user password

When the q process has been started with the -u command to load a password file, the \u command reloads the password file. This allows the password to be changed while the process is running.

See 13.2.17 for the related command line parameter -u.

13.1.24 \v variables

The command \v [ns] displays a sorted list of symbolic names of the variables in the optional ns. In a fresh q session,

q)\v
`symbol$()
q)(a;b):42 43
q)\v
`s#`a`b
q)\v .
`s#`a`b
q).jab.a:42
q)\v .jab
,`a

Tip

To expunge variable a from the root,

q)delete a from `.
`.

13.1.25 \w workspace

The workspace command \w displays information about resource utilization in the current q session. When the parameter is not present, it returns a list of six integers:

0. Number of bytes allocated
1. Number bytes available in heap
2. Maximum heap size used heretofore in session
3. Maximum bytes available as specified at startup in -w
4. Number of bytes for mapped entities
5. Number of bytes of physical (i.e. machine) memory
For a more readable display use .Q.w.

In a fresh q session on the author's laptop:

q)\w
361920 67108864 67108864 0 0 17179869184
q)biddata:til 200000000
q)\w
2147845616 2214592512 2214592512 0 0 17179869184
q).Q.w[]
used| 2147845952
heap| 2214592512
peak| 2214592512
wmax| 0
mmap| 0
mphy| 17179869184
syms| 672
symw| 27901

When the parameter is present, \w 0 returns a list with two items relating to symbol usage: the number of symbols and the corresponding number of bytes of memory used. For example, in a fresh q session on the author's laptop:

q)\w 0
670 27840
q)lotsofsyms:1000000?`5
q)\w 0
645261 36134595

The \w command also allows the workspace size to be increased provided it was set in the startup command line. See the KX Documentation website entry on "-w (workspace)" for details.

13.1.26 \W week offset

The week offset command \W [n] displays or sets the start-of-week offset to n, where 0 is Saturday. The default is 2, i.e Monday. This is useful in controlling weekends when aggregating weekly data. In a fresh q session,

q)\W
2i
q)group `week$2025.01.01+til 10
2024.12.30| 0 1 2 3 4
2025.01.06| 5 6 7 8 9
q)\W 0
q)group `week$2025.01.01+til 10
2024.12.28| 0 1 2
2025.01.04| 3 4 5 6 7 8 9
q)\W 1
q)group `week$2025.01.01+til 10
2024.12.29| 0 1 2 3
2025.01.05| 4 5 6 7 8 9

13.1.27 \x expunge handler

The expunge handler command \x handler un-assigns a user specified event handler for one of the .z.* event handlers and restores the default system behavior. For example, here is how you can customize the console response and then restore the original behavior.

q).z.pi:{"==>",.Q.s value x}
q)42
==>42
q)\x .z.pi
==>q)43
43
q)

Warning

If you expunge .z.ph and certain other handlers this will even remove the implementation that you get on startup, so your HTTP interface will stop working. Check the KX Documentation website for detailed .z handler documentation.

13.1.28 \z date parsing

The date parsing format command \z [0|1] displays or sets the format for date parsing. A value of 0 corresponds to month-then-day – as in mm/dd/yyyy – and a value of 1 corresponds to day-then-month – as in dd/mm/yyyy. The default value is 0i. In a fresh q session,

q)\z
0
q)"D"$"06/01/2010"
2010.06.01
q)\z 1
q)"D"$"06/01/2010"
2010.01.06

See 13.2.20 for the related command line parameter -z.

13.1.29 \1 and \2 redirect

The commands \1 and \2 redirect the OS stdout and stderr from within a q session. Follow the command with a file name for the redirected output. In a fresh q session,

q)\1 data/out.txt
q)1+2*til 5
q)\2 data/err.txt
6*`7
\\
cat data/out.txt
1 3 5 7 9
cat data/err.txt
q)'type

13.1.30 \_ hide q code

The command \_ with no parameter checks to see if client write access is blocked. See the description of --b in 13.2.1.

The command \_ script.q transforms the specified script file into an equivalent script.q_ that can be loaded and executed with \l but whose contents are scrambled for human eyes. The resulting file cannot be viewed, serialized or modified.

Tip

There was a long-running joke in the q community that putting Arthur's source code for k and q through the "obscure code" step actually made it more readable.

For example, suppose we have saved the following script as

/scripts/sensitive.q.
   secret:42
   reveal:{[] 42}
Then we can lock it as follows.

q)\_ sensitive.q
`sensitive.q_
q)\l sensitive.q_
q)secret
42
q)reveal
locked
q)reveal[]
42
q)read0 `:sensitive.q_
"\322\223\306'66\324\016\206'\253\0303S\331\220\242\214LGL\024'\351\361"

13.1.31 \oscmd operating system

The command \oscmd, in which oscmd is any text not recognized as a q command, is assumed to be an operating system command and is passed to the OS for execution. Any output to stdout will be returned to q as strings. This is handy to avoid having to exit the q session and can be done programmatically with the system function. For example, on the author's laptop,

q)\pwd
"/Users/jaborror"
q)\cd Q4M
q)\ls pages
"c.je"
"c.js"
"sample0.html"
"sample1.html"
"sample2.html"

Tip

If oscmd results in an operating system error, an exception will be thrown in q. For safe programmatic execution, you can trap the exception by executing oscmd with system wrapped in protected evaluation.

13.1.32 Interrupt and Terminate (Ctrl+c and Ctrl+z and Ctrl+)

You can interrupt a long-running q function with Ctrl+c. Note that some q functions are so tight that the interrupt may not be registered. You can suspend a q console session using Ctrl+z, (the result is platform dependent). You can terminate a process with extreme prejudice using Ctrl+ . This will result in all un-saved contents of the workspace being lost.

Note

A q process that is terminated will raise a 'stop error.

13.1.33 \ terminate

Use \ to terminate one level of suspended execution arrived at via a Signal.

q)f:{x*y}
q)f[2;`3]
{x*y}
'type
*
2
`3

q))\
q)

Tip

Do not have an itchy trigger finger when exiting multiple levels of suspended evaluation, as \\ will exit the q session immediately.

If you are adventuresome, you can also issue \ at the normal q prompt to toggle between the q interpreter and the k interpreter.

q)\
a:42
-a
-42
\
q)-a
'- 

The same can be achieved while in the debugger with \ (note the extra space).

13.1.34 \\ exit

To exit the q process, enter a double backslash \\ at any console prompt.

q)\\
$

Important

There is no confirmation prompt for \\. The q session is terminated with extreme prejudice.

Tip

For programmatic shutdown, use (exit) and provide a return value that can be piped into other processes.

13.2 Command Line Parameters

When you start q from the command line, you can optionally follow the q executable immediately with a file or directory to be "loaded" upon startup. This is effectively the same as issuing the \l command with that file or directory as the first action in the q session.

Following the q executable and the file name, you can include one or more command line options. Each is prefaced with '-' and followed by whitespace and an optional parameter value. Many of the command line parameters have equivalent q commands that can be issued within the session. You can also include your own options or parameters.

Note

This is different from the UNIX convention, which uses double-dash for long parameter names.

We cover the command line options known at the time of this writing (July 2025). Many of these have equivalent expressions as q commands covered in the previous section where they are explained in greater detail. See the KX Documentation website for the most up-to-date coverage.

13.2.1 -b block database modification

The –b command line parameter disallows connected clients to modify kdb data. This includes setting global variables or modifying files. This behavior is only in effect for operations initiated via remote (i.e., client) connection, so you will not see the effects in a console session on the server process.

13.2.2 -c console

The -c r c parameter specifies a pair of integers for the size of the q virtual console display as rows and columns. The default is the size of the command-shell window which is 24 77 on the author's MacBook.

13.2.3 -C console

The -C r c parameter (upper case) specifies a pair of integers for the size of the HTTP virtual console display as rows and columns. The default setting on the author's laptop is 36 2000i.

13.2.4 -e client error trapping

The –e 0|1|2 parameter enables or disables trapping exceptions arising during processing IPC requests. The default is 0.

13.2.5 -g garbage collection

The -g 0|1 parameter sets the garbage collection behavior. See 13.1.10 for an explanation.

13.2.6 -l and -L logging

The –l parameter starts q with logging of remote requests enabled. Following is a brief description of how logging works; see the KX Documentation website for more information. The -L parameter (upper case) forces disk write on each remote execution. See the entry "Using log files" on the KX site for details.

A logging server uses files with .log and .qdb extensions and name specified immediately after the q executable on the command line that starts q. For example, starting q with

> $q data/logdemo -l
will use files data/logdemo.log and data/logdemo.qdb.

The idea of logging is that each time a remote request is executed, it is logged. Periodically the application issues the \l command to checkpoint the current state of the workspace (more specifically, to serialize and persist the root context) and clear the log.

Should a logging process terminate abruptly, restarting it with the same --l command causes the most recently persisted state to be restored. Specifically, the serialized root context is restored from the .qdb file and requests that were processed after the state was persisted are replayed from the .log file.

Note that although only remote requests are logged, your process can ensure that its own activity is logged by sending requests to itself with the reserved handle 0.

Here is a simple session that demonstrates the logging scenario using local activity. Remote activity works the same.

>q /data/logdemo -l
q)0 "a:42"
q)0 "b:43"
q)\l
q)\\
>q /data/logdemo -l
q)a
42
q)b
4

13.2.7 -m memory domain

The –m path option allows memory to be backed by the file system.

See the .m namespace topic on the KX site for an explanation.

13.2.8 -o UTC offset

The –o n parameter specifies the offset from GMT for q time values. The interpretation of n is hours oif n < 24 and minutes otherwise.

13.2.9 -p port

The –p n parameter opens port n to listen for TCP/IP and HTTP traffic. The default is 0 meaning that no port is open. As of q4.1 a port range can be specified in place of a port number. The range of ports specified as pbegin/pend is inclusive and tried in a random order. See 13.1.14 for details.

13.2.10 -P display precision

The –P n parameter (upper case) specifies the number of digits for floating point display. See 13.1.4 for more information.

13.2.11 -q quiet

The –q parameter starts q quietly, meaning that no start-up banner is displayed and there is no q prompt at the console. Typically used when there is no console session.

13.2.12 -r replicate

The –r parameter starts a replicating q server. See the Using log files: logging, recovery and replication on the KX web site for information on replication.

13.2.13 -s secondary

The –s n parameter starts the q process with n secondary threads for parallel processing. Negative n indicates that separate processes will be available for parallel processing. See Parallel processing on the KX site for information on threading and parallel processing.

13.2.14 -S random seed

The –S n initializes the random seed to n. See "\S" on the KX site for more information.

13.2.15 -t timer

The –t n sets the period to n milliseconds between timer ticks. The default is 0, for timer not enabled. See 13.1.19 for more information.

13.2.16 -T timeout

The –T secs parameter specifies the number of minutes for timeout of remote requests. See 13.1.20 for an explanation.

13.2.17 -u and -U user validation

The parameter –u 1 starts a q session in which all system functions and file access are blocked. This is what you should want in production applications. See the "-u" entry on the KX site for a detailed list of everything that is blocked.

The parameter -U file sets a password file and disables \x. The password file is a text file with one credential on each line. (No trailing blank line/s.)

user1:password1 
user2:password2 
See the "-U" entry on the KX site for details on how this functions.

The parameter -u file combines the two options above.

13.2.18 -w workspace size

The parameter –w n sets the workspace size limit to n MB for the heap across threads for memory domain 0. The default is 0 for no limit. An attempt to allocate more than this amount of memory will result in a ‘wsfull exception and immediate termination of the q process.

13.2.19 -W week start

The parameter –W n (upper case) sets the offset of the beginning of the week to n days after Saturday. See 13.1.25 for the related w command.

13.2.20 -z date parsing format

The parameter –z 0|1 sets the format for "D"$ date parsing to 0 for mm/dd/yyyy and 1 for dd/mm/yyyy.

13.3 System Variables

Variables in the .z namespace expose q environmental information and functions, as well as hooks for callbacks. In this section we explain the basic function of each. See the corresponding entry on the KX Documentation website for the latest updates and more details.

13.3.1 .z.a IP address

The system variable .z.a is an int representing the encoded IP address of the current running q instance. To see the usual four-integer IP address, decode the int using base 256. For example, on the author's laptop,

q).z.a
2130706433i
q)`int$0x0 vs .z.a
127 0 0 1i

13.3.2 .z.ac on access

Assign a handler to the system variable .z.ac to process Single Sign On (SSO) token cookies from the HTTP header. Your handler is passed a two-item list comprising the request text and a dictionary containing the elements of the request header. Your custom code should process the `Authorization value of the dictionary and should return a list in one of the following forms:

  • (0; "") to indicate 401 page not found
  • (1; "*username*") to indicate that username has been validated and to assign this value to .z.u
  • (2; "*raw text*") to send raw response text to the client
  • (4;"") for fallback to basic authentication

Note that .z.ac supersedes .z.pw when defined.

13.3.3 .z.b dependencies

The system variable .z.b is a dictionary that represents the (direct) dependencies of all views (aliases). The keys are symbolic names of entities in the workspace and the associated values are lists of symbolic names of variables that depend directly on the variables named by the key.

In a fresh q session,

q)a::x+y
q)b::x*x
q)c::a+b
q).z.b
x| `a`b
y| ,`a
a| ,`c
b| ,`c

It is a nice exercise to write a q expression that recursively finds all dependencies, not just direct ones. Another nice exercise is to invert the dictionary to relate the name of an entity to everything it depends on.

13.3.4 .z.bm on bad message

The system variable .z.bm represents a handler called when data passed over IPC is not well formed. Upon this event, the function attached to .z.bm is called with a 2-item list of the form

 (handle; msgBytes)
Then the handle is closed and 'badmsg is signaled.

13.3.5 .z.c cores

The system variable .z.c represents the number of cores on the physical machine hosting the q process. Hardware with hyper-threading reports the number of virtual cores.

13.3.6 .z.D local date

The system variable .z.D retrieves the local date component according to the time zone offset from GMT and is equivalent to `date$.z.P.

13.3.7 .z.d UTC date

The system variable .z.d retrieves the date component of Greenwich Mean Time (GMT) and is equivalent to `date$.z.p.

13.3.8 .z.e TLS connection status

TLS details used with a connection handle. Returns an empty dictionary if the connection is not TLS enabled. Where h is a connection handle.

q)h ".z.e"
CIPHER | `AES128-GCM-SHA256
PROTOCOL| `TLSv1.2
CERT
|`SUBJECT`ISSUER`SERIALNUMBER`NOTVALIDBEFORE`NOTVALIDAFTER`VERIFIED`VERIFYERROR!...

13.3.9 .z.ex failed primitive

In a debugger session, .z.ex is set to the failed primitive.

q){2+`3}[]
'type
[1] {2+`3}
     ^
q)).z.ex
+

13.3.10 .z.ey failed argument

In a debugger session .z.ey is set to the offending argument(s).

q){2+`3}[]
'type
[1] {2+`3}
     ^
q)).z.ey
2
`3

13.3.11 .z.exit on exit

The system variable .z.exit specifies a unary function to be called in order to clean up resources just prior the q process exit.

Important

The handler cannot cancel the exit.

The parameter passed to the handler is 0i if the exit was invoked manually with \\ or it is the argument to the (exit) function when that was called programmatically.

In a fresh q session,

q).z.exit:{show x}
q)\\
0i

In another fresh q session,

q).z.exit:{show x}
q)exit 43
43i

Note that if the handler itself throws an exception – deliberate or otherwise – the session will be suspended at that error.

q).z.exit:{'bad}
q)exit 0
{'bad}
'bad
q))

Tip

The default exit behavior can be restored by expunging with \x.

13.3.12 .z.f startup file

The system variable .z.f is a symbol representing the file parameter entered on the q start-up command line. For example,

$ q Q4M/scripts/answer.q
q).z.f 
`Q4M/scripts/answer.q 

13.3.13 .z.H active sockets

The variable .z.H is a sorted list of the current active sockets.

13.3.14 .z.h host

The variable .z.h is a symbol representing the network name of the host running the q instance, which is the same as the OS command hostname on Unix. For example, on the author's laptop,

q).z.h
`jeffrys-macbook-pro.local

13.3.15 .z.i process ID

The variable .z.i is an int representing the process id of the running q instance. For example, on the author's laptop,

q).z.i
56548i

13.3.16 .z.K release version

The system variable .z.K is a float value representing the major version of the running q instance. For example, on the author's laptop,

q).z.K
4.1

13.3.17 .z.k release date

The system variable .z.k is a date value representing the release date of the running q instance. For example, on the author's laptop,

q).z.k
2024.07.08

13.3.18 .z.l license

The system variable .z.l is a list of strings containing information about the license of the running kdb+ instance. The most useful are the items in indices 1 and 2, which represent the expiry date and update date, respectively. For example, on a system long, long ago,

q).z.l
("";"2007.07.01";"2007.07.01";,"1";,"1";,"0";,"0")

Tip

The value of .z.l is () for 32--bit non-production versions of q.

13.3.19 .z.N local timespan

The system variable .z.N retrieves the nanosecond local timespan component according to the time zone offset from GMT and is equivalent to `timespan$.z.P.

13.3.20 .z.n UTC timespan

The system variable .z.n retrieves the nanosecond timespan component of Greenwich Mean Time (GMT) and is equivalent to `timespan$.z.p.

13.3.21 .z.o OS

The system variable .z.o is a symbol representing the version of kdb+ running and not the actual OS. For example, this text is being written on a 64-bit Mac system.

q).z.o
`m64

13.3.22 .z.P local timestamp

The system variable .z.P displays the current local nanosecond resolution from .z.p according to the time zone offset.

For example, at the exact time of this writing in the Hawaii time zone we find,

q).z.P
2025.07.05D01:26:04.674851000

13.3.23 .z.p UTC timestamp

The system variable .z.p retrieves the current Greenwich Mean Time (GMT) with nanosecond resolution. It is the basis for all other date and time values in the .z namespace.

For example, at the exact time of this writing,

q).z.p
2025.07.05D11:27:38.124455000

13.3.24 .z.pc on process close

Assign a q handler to the system variable .z.pc to be invoked after a connection is closed. At the point your handler is invoked, the other variables associated with the connection – e.g., .z.w – have already been wiped.

The handle of the connection that has just been closed is passed as the lone parameter to your function so that you can clean up any resources associated with it in your application.

To reset to the default setting, expunge the handler with \x .z.pc.

13.3.25 .z.pd peach distribution

Assign an int list or q function representing an event handler to the system variable .z.pd for use by (peach) for a q process that has been started with the –s command line parameter with a negative value.

Your handler supplies a list of ints representing open handles to other processes and will be called by (peach) when it distributes work to those processes.

These handles must not be used for other processing as (peach) will close any handle that presents data it is not expecting. See Peach for more.

Important

The int return list of your handler must have the `u# attribute applied.

Here is a simple example that opens and returns five handles on the local machine starting at port 20000. It assumes that worker processes have already been started with these ports open. See the KX site for more comprehensive examples:

q).z.pd:{`u#hopen each 20000+til 5} 

13.3.26 .z.pg on synchronous message

Assign a unary function to the system variable .z.pg to be invoked with the object passed whenever a remote client q process makes a synchronous request – a.k.a. "process get." The name derives from the fact that a synchronous call has "get" semantics. The default behavior executes system on the incoming message in the root context.

To reset to the default setting, expunge the handler with \x .z.pg.

13.3.27 .z.ph on HTTP get

Assign a unary function to the system variable .z.ph to be evaluated whenever a synchronous HTTP request is received by the current q process. See 11.10.1 for a detailed discussion of the message format.

If you reset to the default setting by expunging the handler with \x .z.ph you will have no handler at all, which stops the HTTP interface from working.

13.3.28 .z.pi on input

Assign a function to the system variable .z.pi to be evaluated when q receives user input from the console – a.k.a. "process input." For example, the following mimics the console display of pre-2.4 q versions.

q).z.pi:{0N!value x;} 
q)([] c1:`a`b`c; c2:10 20 30) 
+`c1`c2!(`a`b`c;10 20 30) 
To reset to the default behavior, expunge the handler with \x .z.pi.

13.3.29 .z.pm HTTP options method

Assign a unary function to the system variable .z.pm to receive HTTP OPTIONS as,

 (`OPTIONS;requestText;requestHeaderDict) 

For the POST method use  .z.pp, and for GET use .z.ph.

13.3.30 .z.po on open

Assign a unary function to the system variable .z.po to be evaluated after a connection to the current q process has been successfully opened – i.e. after it’s been validated against any -u/-U file and .z.pw check. The local handle of the connecting process is passed as the parameter. See 11.6 for a discussion.

To reset to the default setting, expunge the handler with \x .z.po.

13.3.31 .z.pp on HTTP post

Assign a unary function to the system variable .z.pp to be evaluated whenever an HTTP post is routed to the current q process. See 11.7 for a discussion of .z.pg, whose parameters are the same.

There is no .z.pp default setting but an example would be that it calls system on the first item of its argument and returns the result to the calling task.

13.3.32 .z.pq on qcon

Assign a unary function to the system variable .z.pq to process input from remote connections using the qcon text protocol. This handles remote qcon connections without defining special handling for console processing in .z.pi. It defaults to calling .z.pi.

13.3.33 .z.ps on set

Assign a unary function to the system variable .z.ps to be evaluated whenever a client process sends an asynchronous message to the current q process – a.k.a. "process set." The name derives from the fact that an asynchronous call has set semantics. The parameter passed to your handler is the message content. The default behavior is to invoke system.

Note

Use .z.ps in preference to .z.pg when messages are sent to the local process using handle 0.

To reset the to the default setting, expunge the handler with \x .z.ps.

13.3.34 .z.pw on password validate

Assign a binary function to the system variable .z.pw to be evaluated after the command line –u and –U checks but before the .z.po handler. This can be used to implement authorization – e.g., access LDAP. Your handler should accept two parameters: a symbolic user name and a password string. It should return a boolean pass/fail indicator. If .z.pw returns 0b the task attempting to establish the connection will signal an 'access error

The default definition is {[user;pswd]1b}. To reset to the default setting, expunge the handler with \x .z.pw.

13.3.35 .z.q quiet mode

The system variable .z.q is a read-only boolean indicating whether q was started in Quiet Mode using the –q 1 command line parameter.

13.3.36 .z.r block

The system variable .z.r is a read-only boolean indicating whether an update in the current context would be blocked. Returns 1b during execution:

  • in reval
  • when the -b command-line option has been set
  • in a thread other than the main event thread

13.3.37 .z.s self

The system variable .z.s represents the current function during function application. This can be useful when writing recursive functions but there is usually a better way to do this using iterators. For example, here is a stack-eating recursive factorial.

q){$[x=1;x;x*.z.s x-1]} 10 / Don't do this at home kiddos
3628800

Zen moment

Be mindful when writing explicitly recursive functions in q as there is no notion of tail call optimization so you can quickly exhaust the stack and blow up your program. Use one of the iterators instead. For the philosophically inclined, a modest meditation will reveal that tail call optimization is morally equivalent to converting explicit recursion to an iterator.

13.3.38 .z.T local time

The system variable .z.T retrieves the local time component according to the time zone offset from GMT and is equivalent to `time$.z.P.

13.3.39 .z.t GMT time

The system variable .z.t retrieves the time component of Greenwich Mean Time (GMT) and is equivalent to `time$.z.p.

13.3.40 .z.ts on timer

Assign a unary function to the system variable .z.ts to be evaluated on every timer tick – see 13.1 for the command \t to start/stop the timer. For example, the following assigns a handler to display local time to the console, turns on the timer to fire (approximately) every two seconds and turns it off after a few ticks.

q).z.ts:{show .z.P}
q)\t 2000
q)2025.07.05D03:31:36.213451000
2025.07.05D03:31:38.216386000
2025.07.05D03:31:40.214967000
2025.07.05D03:31:42.213775000
\t 0

To restore the default behavior, expunge the handler with \x .z.ts.

Note

When q has completed executing a script passed as a command-line argument, and if there are no open sockets nor a console, it will exit. The ticking timer alone is not enough to stop the process exiting – it must have an event source which is a file descriptor (socket, console, or some plugin registering a file descriptor and callback via the C API sd1 function).

13.3.41 .z.u user ID

The system variable .z.u is a symbol that represents the user id of the q session. For handle 0 – i.e., the console – it contains the user of that session.

q).z.u
`jaborror

During IPC processing, on the server side .z.u contains theuserid passed through hopen by the client process. On the client side of the connection .z.u contains the null symbol.

13.3.42 .z.vs on value set

Assign a binary function to the system variable .z.vs to be evaluated after a global variable in the root context is set. The parameters for your handler are the symbolic name of the global being set and the subdomain of the assignment. For example, in a fresh q session,

q)a:42
q)m:(1 2; 3 4)
q).z.vs:{0N!(x;y;value x)}
q)a:43
(`a;();43)
q)m[0;0]:42
(`m;0 0;(42 2;3 4))
To restore the default behavior, expunge the handler with \x .z.vs.

13.3.43 .z.W handles

The system variable .z.W represents a dictionary of IPC handles with the number of bytes waiting in their output queues. At the console prompt,

q)h:hopen `:localhost:5042 
q)h 
6i 
// send a large request and immediately display .z.W 
q)neg[h]({};til 1000000); neg[h]({};til 10); .z.W 
6| 8000140 
             / wait a moment 
q).z.W 
6| 0 

Since 4.1 2023.09.15, this returns handles!bytes as I!J.

13.3.44 .z.w handle

The system variable .z.w represents the handle of “who” is in communication during the processing of a remote call. At the a console prompt, the value is 0i, representing the interactive user. In the midst of processing a remote message, it is the (local) open handle associated with that remote client on this process.

13.3.45 .z.wc on websocket close

The system variable .z.wc can be assigned a handler that is called when a websocket connection is closed. The handler is executed immediately after a websocket connection has been closed. Since the connection has been closed by the time the handler is called, there are no valid remote values for .z.a, .z.u or .z.w. Consequently the local values are returned.

Tip

This is useful to cleanup things like a table of users keyed by handle, in which case you use the just-closed handle that is passed as a parameter to .z.ac.

13.3.46 .z.wo on websocket open

Assign a unary function to system variable .z.wo that is called when a websocket conection is opened. The handler is executed just after a websocket connection to a kdb+ session has been initialized – i.e., once it has been validated against a -u/-U file (if specified) and .z.pw checks. The argument is the just-opened handle.

Tip

This handler is typically used to build a dictionary of handles associated with session information such as .z.a or .z.u.

13.3.47 .z.ws on websocket message

Assign a unary function to the system variable .z.ws to be invoked when a message arrives over a WebSocket. If the incoming message is text, the argument is a string; for a binary message it is a byte vector. See 11.10 for examples.

13.3.48 .z.X raw command line

The system variable .z.X contains a list of strings of the raw, unfiltered command line with which q was invoked, including the name under which q was invoked, as well as single-letter arguments.

~ % q myfile.q -myarg 42 -p localhost:5042  

KDB+ 4.1 2024.07.08 Copyright (C) 1993-2024 Kx Systems  
q).z.X 
"/Users/jaborror/q/m64/q" 
"myfile.q" 
"-myarg" 
"42" 
"-p" 
"localhost:5042" 

13.3.49 .z.x command line parameters

The system variable .z.x contains a list of strings representing the command line parameters provided after the name of the file or directory on the command line invocation of the q process. For example, if q is invoked from the OS console with,

q convertargs.q 42 forty 2.0

we find,

q).z.f
`convertargs.q
q).z.x
("42";"forty";"2.0")
q).Q.opt .z.x
myarg| "42"

13.3.50 .z.Z local datetime ()

The system variable .z.Z contains the local date component according to the time zone offset from GMT and is equivalent to `datetime$.z.P.

Note

This is deprecated in favor of .z.P.

13.3.51 .z.z GMT datetime

The system variable .z.z contains the GMT date component and is equivalent to `datetime$.z.p.

Note

This is deprecated in favor of .z.P.

13.3.52 .z.zd compression/encryption defaults

The system variable .z.zp displays or sets a list of parameters for data compression. You assign in two ways. First as

.z.zd:(lbs;alg;lvl)

Where the integers lbsalg, and lvl are compression parameters and/or encryption parameters. They set default values for logical block size, compression/encryption algorithm and compression level that apply when saving to files with no file extension. For example,

q).z.zd:17 2 6 / set zip defaults
q)\x .z.zd / clear zip defaults

You can also assign a dictionary to .z.zd. The keys of the dictionary are either column names or the null symbol `. The associated value of each entry is an integer vector: (lbs; alg; lvl) as before. The null symbol is used as a default for columns that do not match the other keys.

q)show dict:``a`b!(17 5 3;17 2 6;17 2 6) / default compression is
`zstd` with level 3
| 17 5 3
a| 17 2 6
b| 17 2 6
q).z.zd:dict