CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Processes

Modules

 Overview
 

Data Structures

struct  ProcessInfo
 
struct  ProcessOpts
 
struct  Process
 

Macros

#define PROCESS_InvalidID   ((ProcessID)-1)
 A process id that does not refer to anything.
 
#define PROC_ExitCodeUnknown   ((int32)-1)
 
#define procRelease(pproc)   objRelease(pproc)
 

Typedefs

typedef int64 ProcessID
 Operating system process id.
 
typedef struct ProcessInfo ProcessInfo
 
typedef enum ProcStdioEnum ProcStdio
 Where a launched process's standard input, output and error go.
 
typedef struct ProcessOpts ProcessOpts
 
typedef struct Process Process
 

Enumerations

enum  ProcEnumFlags { PROC_EnumFullPath = 0x0001 }
 Flags for procEnum() and procFind() More...
 
enum  ProcStdioEnum { PROC_StdioInherit = 0 , PROC_StdioNull , PROC_StdioFile }
 Where a launched process's standard input, output and error go. More...
 
enum  ProcLaunchFlags { PROC_Detached = 0x0001 , PROC_NewGroup = 0x0002 , PROC_NoWindow = 0x0004 , PROC_NewConsole = 0x0008 }
 Flags for procLaunch() More...
 

Functions

void procInfoInit (ProcessInfo *info)
 
void procInfoDestroy (ProcessInfo *info)
 
void procInfoCopy (ProcessInfo *dest, const ProcessInfo *src)
 
bool procEnum (sa_ProcessInfo *out, flags_t flags)
 
bool procFind (sa_ProcessInfo *out, strref name, flags_t flags)
 
bool procGetInfoByID (ProcessInfo *out, ProcessID pid, flags_t flags)
 
bool procGetInfo (ProcessInfo *out, Process *proc, flags_t flags)
 
ProcessID procCurrentID (void)
 
void procOptsInit (ProcessOpts *opts)
 
void procOptsDestroy (ProcessOpts *opts)
 
void procOptsSetEnv (ProcessOpts *opts, strref name, strref val)
 
void procOptsUnsetEnv (ProcessOpts *opts, strref name)
 
ProcessprocLaunch (strref exe, sa_string args, ProcessOpts *opts)
 
ProcessprocOpen (ProcessID pid)
 
ProcessID procID (Process *proc)
 
bool procRunning (Process *proc)
 
bool procWait (Process *proc, int64 timeout)
 
bool procExitCode (Process *proc, int32 *code)
 
bool procTerminate (Process *proc, bool force)
 
bool procNotifyExit (Process *proc, closure cls)
 
void procNotifyCancel (Process *proc)
 
bool procName (Process *proc, string *out)
 
bool procExePath (Process *proc, string *out)
 

Detailed Description

Macro Definition Documentation

◆ PROC_ExitCodeUnknown

#define PROC_ExitCodeUnknown   ((int32)-1)

Exit code given to exit callbacks when a process finished but its exit code cannot be read

Only happens on Unix, for a process cx did not launch. Windows always reports the real code, which may itself be -1.

Definition at line 137 of file process.h.

◆ procRelease

#define procRelease (   pproc)    objRelease(pproc)

void procRelease(Process **pproc);

Releases a reference to a process handle.

The handle is destroyed once the last reference goes, and the pointer is set to NULL. This does nothing to the process itself.

Parameters
pprocPointer to the handle to release

Example:

procRelease(&proc);
#define procRelease(pproc)
Definition process.h:430

Definition at line 430 of file process.h.

Typedef Documentation

◆ Process

typedef struct Process Process

A process cx launched or attached to

This is a base class; the platform layer provides the derived class holding the native handle. Release it with procRelease() when finished.

Definition at line 19 of file processobj.h.

◆ ProcessInfo

typedef struct ProcessInfo ProcessInfo

One process in a snapshot of the running process list

Follows the Init/Destroy pattern: the struct itself is the caller's, and procInfoDestroy() releases what is inside it without freeing the struct.

◆ ProcessOpts

typedef struct ProcessOpts ProcessOpts

Options for procLaunch()

Initialize with procOptsInit() and clean up with procOptsDestroy(). Passing NULL to procLaunch() instead inherits everything from the calling process.

Paths are ordinary cx paths, the same as the fs functions take. A relative path is relative to the caller's current directory.

Enumeration Type Documentation

◆ ProcEnumFlags

Flags for procEnum() and procFind()

Enumerator
PROC_EnumFullPath 

Also resolve each process's full executable path.

Much slower, and the path is still unreadable for processes belonging to other users. 

Definition at line 160 of file process.h.

◆ ProcLaunchFlags

Flags for procLaunch()

Enumerator
PROC_Detached 

Put the child in its own session so it outlives the caller.

PROC_NewGroup 

Give the child its own process group, so it can be signalled as a group.

PROC_NoWindow 

Windows: do not give the child a console window. Ignored elsewhere.

PROC_NewConsole 

Windows: give the child its own console window. Ignored elsewhere.

Cannot be combined with PROC_Detached or PROC_NoWindow, on any platform. With
PROC_StdioInherit the child uses the new console for its stdin, stdout and stderr;
with the other stdio modes its output still goes where they send it. 

Definition at line 299 of file process.h.

◆ ProcStdioEnum

Where a launched process's standard input, output and error go.

Enumerator
PROC_StdioInherit 

The child shares the caller's stdin, stdout and stderr.

PROC_StdioNull 

The child's stdio is discarded (/dev/null, or NUL on Windows)

PROC_StdioFile 

The child's stdout and stderr both go to ProcessOpts::stdioPath.

The file is created if it does not exist and appended to if it does. Output from both
streams is written to the one file in the order it happens. Other programs can read the
file while the child writes to it, and on Windows can also rename or delete it. The
child's stdin is discarded, as with PROC_StdioNull. 

Definition at line 285 of file process.h.

Function Documentation

◆ procCurrentID()

ProcessID procCurrentID ( void  )

Returns the id of the calling process.

Returns
This process's id

Example:

ProcessID procCurrentID(void)
int64 ProcessID
Operating system process id.
Definition process.h:128

◆ procEnum()

bool procEnum ( sa_ProcessInfo *  out,
flags_t  flags 
)

Lists the processes running on the machine.

Parameters
outReceives the list; initialized by this call, destroy it with saDestroy()
flagsOptional ProcEnumFlags
Returns
true on success, false if the process list could not be read at all

Example:

sa_ProcessInfo procs;
if (procEnum(&procs, 0)) {
foreach (sarray, i, ProcessInfo, p, procs) {
// use p.pid and p.name
}
saDestroy(&procs);
}
#define saDestroy(handle)
Definition sarray.h:345
bool procEnum(sa_ProcessInfo *out, flags_t flags)

◆ procExePath()

bool procExePath ( Process proc,
string *  out 
)

Reads the full path to a process's executable.

Frequently unavailable for processes belonging to other users, in which case this returns false and clears the output.

Parameters
outReceives the path; prior contents are destroyed
procProcess handle
Returns
true if a path could be read

Example:

string path = 0;
if (procExePath(proc, &path)) {
// use path
}
strDestroy(&path);
void strDestroy(strhandle ps)
bool procExePath(Process *proc, string *out)

◆ procExitCode()

bool procExitCode ( Process proc,
int32 *  code 
)

Reads the exit code of a finished process.

Only meaningful once the process has finished. See the overview for the one case this cannot answer: a process on Unix that cx did not launch itself.

Parameters
procProcess handle
codeReceives the exit code
Returns
true if an exit code is available; sets cxerr to CX_NotSupported where it can never be

Example:

int32 code;
if (procExitCode(proc, &code)) {
// the process exited with 'code'
}
bool procWait(Process *proc, int64 timeout)
bool procExitCode(Process *proc, int32 *code)
#define timeForever
Maximum representable time value (approximately year 294,276 CE)
Definition time.h:15

◆ procFind()

bool procFind ( sa_ProcessInfo *  out,
strref  name,
flags_t  flags 
)

Lists the running processes whose name matches.

Matching ignores case, and an ".exe" suffix on either side, on every platform. Looking for "test_runner" therefore finds "test_runner.exe" on Windows.

Parameters
outReceives the matching processes; initialized by this call, destroy it with saDestroy()
nameProcess name to look for
flagsOptional ProcEnumFlags
Returns
true on success, false if the process list could not be read at all

Example:

sa_ProcessInfo found;
if (procFind(&found, _SL("test_runner"), 0)) {
// saSize(found) processes are running under that name
saDestroy(&found);
}
#define _SL(s)
Inline ASCII string literal with compile-time embedded length (STR_LEN8). Content must be < 200 bytes...
Definition strliteral.h:207
bool procFind(sa_ProcessInfo *out, strref name, flags_t flags)

◆ procGetInfo()

bool procGetInfo ( ProcessInfo out,
Process proc,
flags_t  flags 
)

Looks up the process a handle refers to.

Parameters
outInitialized structure to fill in
procProcess to look up
flagsOptional ProcEnumFlags
Returns
true if the process exists, false otherwise

Example:

procInfoInit(&info);
procGetInfo(&info, proc, 0);
bool procGetInfo(ProcessInfo *out, Process *proc, flags_t flags)
void procInfoDestroy(ProcessInfo *info)
void procInfoInit(ProcessInfo *info)

◆ procGetInfoByID()

bool procGetInfoByID ( ProcessInfo out,
ProcessID  pid,
flags_t  flags 
)

Looks up one process by id.

Parameters
outInitialized structure to fill in
pidProcess to look up
flagsOptional ProcEnumFlags
Returns
true if the process exists, false otherwise

Example:

procInfoInit(&info);
// use info.name
}
bool procGetInfoByID(ProcessInfo *out, ProcessID pid, flags_t flags)
@ PROC_EnumFullPath
Also resolve each process's full executable path.
Definition process.h:164

◆ procID()

ProcessID procID ( Process proc)

Returns the id of the process a handle refers to.

Parameters
procProcess handle
Returns
The process id

Example:

ProcessID pid = procID(proc);
ProcessID procID(Process *proc)

◆ procInfoCopy()

void procInfoCopy ( ProcessInfo dest,
const ProcessInfo src 
)

Copies one ProcessInfo over another.

Parameters
destInitialized structure to copy into; its previous contents are released
srcStructure to copy from

Example:

procInfoInit(&copy);
procInfoCopy(&copy, &list.a[0]);
void procInfoCopy(ProcessInfo *dest, const ProcessInfo *src)

◆ procInfoDestroy()

void procInfoDestroy ( ProcessInfo info)

Releases everything inside a ProcessInfo, leaving the struct itself in place.

Parameters
infoStructure to clean up

Example:

◆ procInfoInit()

void procInfoInit ( ProcessInfo info)

Initializes a ProcessInfo to empty.

Parameters
infoStructure to initialize

Example:

procInfoInit(&info);

◆ procLaunch()

Process * procLaunch ( strref  exe,
sa_string  args,
ProcessOpts opts 
)

Launches a program.

Parameters
exePath to the executable to run
argsArguments to pass, not counting the program name itself, which cx supplies
optsLaunch options, or NULL to inherit everything from this process
Returns
A handle to the new process, or NULL if it could not be started; sets cxerr. Fails with CX_InvalidArgument for conflicting options, and with a file error if PROC_StdioFile cannot open its file.

Example:

sa_string args;
saInit(&args, string, 2);
saPush(&args, string, _SL("--verbose"));
Process* proc = procLaunch(_SL("/usr/bin/tool"), args, NULL);
if (proc) {
procRelease(&proc);
}
saDestroy(&args);
#define saInit(out, type, capacity,...)
Definition sarray.h:315
#define saPush(handle, type, elem,...)
Definition sarray.h:460
Process * procLaunch(strref exe, sa_string args, ProcessOpts *opts)

◆ procName()

bool procName ( Process proc,
string *  out 
)

Reads the name of the process a handle refers to.

Parameters
outReceives the name; prior contents are destroyed
procProcess handle
Returns
true if a name could be read

Example:

string name = 0;
procName(proc, &name);
strDestroy(&name);
bool procName(Process *proc, string *out)

◆ procNotifyCancel()

void procNotifyCancel ( Process proc)

Cancels every exit callback registered on a process.

Waits for a callback that is already running to finish, so once this returns nothing the callback touches is still in use. Calling it from inside an exit callback returns immediately instead, since waiting there would wait on itself forever.

For a process cx did not launch, this also stops watching it and lets go of the reference the watch was holding. Releasing the last reference to a process does this automatically.

Parameters
procProcess to stop watching

Example:

void procNotifyCancel(Process *proc)

◆ procNotifyExit()

bool procNotifyExit ( Process proc,
closure  cls 
)

Asks to be told when a process exits.

The closure is called with the process id and its exit code: closureCall(cls, stvar(int64, pid), stvar(int32, exitcode)). The exit code is PROC_ExitCodeUnknown where it cannot be read. Several callbacks can be registered on one process. If the process has already finished, the closure is called before this returns, on the calling thread.

Takes ownership of the closure, even when it returns false; do not destroy it afterwards.

Parameters
procProcess to watch
clsClosure to call when it exits
Returns
true if the closure was registered or already called; false if the process cannot be watched, in which case the closure is destroyed without being called

Example:

static bool onExit(stvlist* cvars, stvlist* args) {
int64 pid; int32 code;
stvlNext(args, int64, &pid);
stvlNext(args, int32, &code);
// the process finished with 'code'
return true;
}
#define closureCreate(func,...)
Definition closure.h:135
#define stvNone
Definition stvar.h:178
#define stvlNext(list, type, pvar)
Definition stvar.h:772
bool procNotifyExit(Process *proc, closure cls)

◆ procOpen()

Process * procOpen ( ProcessID  pid)

Attaches to a process that is already running.

Parameters
pidProcess to attach to
Returns
A new handle, or NULL if the process does not exist or cannot be opened; sets cxerr

Example:

Process* proc = procOpen(pid);
if (proc)
procRelease(&proc);
Process * procOpen(ProcessID pid)

◆ procOptsDestroy()

void procOptsDestroy ( ProcessOpts opts)

Releases everything inside a ProcessOpts, leaving the struct itself in place.

Parameters
optsOptions to clean up

Example:

void procOptsDestroy(ProcessOpts *opts)

◆ procOptsInit()

void procOptsInit ( ProcessOpts opts)

Initializes launch options to "inherit everything".

Parameters
optsOptions to initialize

Example:

procOptsInit(&opts);
void procOptsInit(ProcessOpts *opts)

◆ procOptsSetEnv()

void procOptsSetEnv ( ProcessOpts opts,
strref  name,
strref  val 
)

Sets an environment variable in the child, on top of what it inherits.

Parameters
optsOptions to modify
nameVariable name
valValue to give it; NULL or empty gives the child an empty variable

Example:

procOptsSetEnv(&opts, _SL("CX_MODE"), _SL("fast"));
void procOptsSetEnv(ProcessOpts *opts, strref name, strref val)

◆ procOptsUnsetEnv()

void procOptsUnsetEnv ( ProcessOpts opts,
strref  name 
)

Removes an inherited environment variable from the child.

This is separate from procOptsSetEnv() with an empty value, because removing a variable and setting it to nothing are different things to the program that reads it.

Parameters
optsOptions to modify
nameVariable name

Example:

procOptsUnsetEnv(&opts, _SL("LD_PRELOAD"));
void procOptsUnsetEnv(ProcessOpts *opts, strref name)

◆ procRunning()

bool procRunning ( Process proc)

Checks whether a process is still running.

Parameters
procProcess handle
Returns
true if the process is still running

Example:

if (procRunning(proc)) {
// still alive
}
bool procRunning(Process *proc)

◆ procTerminate()

bool procTerminate ( Process proc,
bool  force 
)

Asks a process to stop, or forces it to.

A polite request lets the process shut down on its own terms and can be ignored; a forced stop cannot be caught and gives the process no chance to clean up.

Parameters
procProcess handle
forcefalse asks the process to stop (SIGTERM); true kills it outright (SIGKILL, or TerminateProcess on Windows, which is always immediate)
Returns
true if the request was delivered

Example:

procTerminate(proc, false);
if (!procWait(proc, timeS(5)))
procTerminate(proc, true);
bool procTerminate(Process *proc, bool force)
#define timeS(s)
Definition time.h:20

◆ procWait()

bool procWait ( Process proc,
int64  timeout 
)

Waits for a process to finish.

Parameters
procProcess handle
timeoutHow long to wait, in microseconds; timeForever waits indefinitely
Returns
true if the process has finished, false if the timeout ran out first

Example:

if (!procWait(proc, timeS(5))) {
// still running after five seconds
procTerminate(proc, false);
}