Task Control Interfaces
Task Control Interfaces
Warning
This section name is duplicate with the first, how should it be named?
Scheduler locking interfaces. These non-standard interfaces are used to enable and disable pre-emption and to test is pre-emption is currently enabled.
Task synchronization interfaces are used to wait for termination of child tasks.
Task Exit Hooks may be used to register callback functions that are executed when a task group terminates. A task group is the functional analog of a process: It is a group that consists of the main task thread and of all of the pthreads created by the main task thread or any of the other pthreads within the task group. Members of a task group share certain resources such as environment variables, file descriptors,
FILEstreams, sockets, pthread keys and open message queues.Note
Behavior of features related to task group’s depend of NuttX configuration settings. See the discussion of “Parent and Child Tasks,” below. See also theNuttX Taskingpage and theTasks vs. Threads FAQfor additional information on tasks and threads in NuttX.
A task group terminates when the last thread within the group exits.
Parent and Child Tasks
The task synchronization interfaces historically depend upon parent and child relationships between tasks. But default, NuttX does not use any parent/child knowledge. However, there are three important configuration options that can change that.
CONFIG_SCHED_HAVE_PARENT: If this setting is defined, then it instructs NuttX to remember the task ID of the parent task when each new child task is created. This support enables some additional features (such asSIGCHLD) and modifies the behavior of other interfaces. For example, it makeswaitpid()more standards complete by restricting the waited-for tasks to the children of the caller.
CONFIG_SCHED_CHILD_STATUS: If this option is selected, then the exit status of the child task will be retained after the child task exits. This option should be selected if you require knowledge of a child process’s exit status. Without this setting,wait(),waitpid()orwaitid()may fail. For example, if you do:This may fail because the child task may run to completion before the wait begins. There is a non-standard work-around in this case: The above sequence will work if you disable pre-emption using
sched_lock()prior to starting the child task, then re-enable pre-emption withsched_unlock()after the wait completes. This works because the child task is not permitted to run until the wait is in place.The standard solution would be to enable
CONFIG_SCHED_CHILD_STATUS. In this case the exit status of the child task is retained after the child exits and the wait will successful obtain the child task’s exit status whether it is called before the child task exits or not.This option is on by default in a kernel build (
CONFIG_BUILD_KERNEL). There, programs start other programs withposix_spawn(),vfork()andexec(), and POSIX requires that a parent can get the exit status of a child that exited before the parent waits for it.
CONFIG_PREALLOC_CHILDSTATUS. To prevent runaway child status allocations and to improve allocation performance, child task exit status structures are pre-allocated when the system boots. This setting determines the number of child status structures that will be pre-allocated.Obviously, if tasks spawn children indefinitely and never have the exit status reaped, then you may have a memory leak! (See Warning below)
Warning
If you enable the CONFIG_SCHED_CHILD_STATUS feature,
then your application must either (1) take responsibility for reaping
the child status with wait(), waitpid() or waitid(), or (2)
suppress retention of child status. If you do not reap the child status,
then you have a memory leak and your system will eventually fail.
Retention of child status can be suppressed on the parent using logic like:
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = SA_NOCLDWAIT;
int ret = sigaction(SIGCHLD, &sa, NULL);A later sigaction() for SIGCHLD without SA_NOCLDWAIT (and
not SIG_IGN) keeps the child status again. While the status is not
kept, wait(), waitpid() and waitid() block until all
children exit and then fail with ECHILD. NuttX decides when a child
is created if its status is kept: a child created while the status is
not kept does not become waitable later.
Functions
int sched_lock(void) : Disables context switching by Disabling addition of new tasks to the ready-to-run task list. The task that calls this function will be the only task that is allowed to run until it either calls sched_unlock (the appropriate number of times) or until it blocks itself.
Returns:
: OK or ERROR.
**POSIX Compatibility:** This is a NON-POSIX interface. VxWorks provides
the comparable interface:
```cSTATUS taskLock(void);
<a id="c.sched_unlock"></a> int sched\_unlock(void)
: Decrements the preemption lock count.
Typically this is paired with sched\_lock() and concludes a critical
section of code. Preemption will not be unlocked until sched\_unlock()
has been called as many times as sched\_lock(). When the lockCount is
decremented to zero, any tasks that were eligible to preempt the current
task will execute.
Returns:
: OK or ERROR.
**POSIX Compatibility:** This is a NON-POSIX interface. VxWorks provides
the comparable interface:
```c
STATUS taskUnlock(void);int32_t sched_lockcount(void) : Returns the current value of the lockCount. If zero, preemption is enabled; if non-zero, this value indicates the number of times that sched_lock() has been called on this thread of execution.
Returns:
: The current value of the lockCount.
**POSIX Compatibility:** None.ipid_t waitpid(pid_t pid, int *stat_loc, int options) : Note
The following discussion is a general description of the
`waitpid()` interface. However, as of this writing, the
implementation of `waitpid()` is incomplete (but usable). If
`CONFIG_SCHED_HAVE_PARENT` is defined, `waitpid()` will be a
little more compliant to specifications. Without
`CONFIG_SCHED_HAVE_PARENT`, `waitpid()` simply supports waiting
for any task to complete execution. With
`CONFIG_SCHED_HAVE_PARENT`, `waitpid()` will use `SIGCHLD` and
can, therefore, wait for any child of the parent to complete, and it
is `waitid()` with a status in place of the `siginfo_t`.
`WUNTRACED` and `WCONTINUED` report a child that stopped on
`SIGSTOP`, `SIGTSTP`, `SIGTTIN` or `SIGTTOU` and a child that
continued on `SIGCONT` (`CONFIG_SIG_SIGSTOP_ACTION`), as the job
control of a shell needs. A `pid` of 0 or less than -1 selects a
process group: with `CONFIG_SCHED_PROCESS_GROUPS` the process groups
of `setpgid()`; without it a process group contains only one
process. NuttX keeps the status of an exited child only with
`CONFIG_SCHED_CHILD_STATUS`: without it, if `waitpid()` is called
after a task has exited, then no status will be available.
The `waitpid()` functions will obtain status information pertaining to
one of the caller’s child processes. The `waitpid()` function will
suspend execution of the calling thread until status information for one
of the terminated child processes of the calling process is available,
or until delivery of a signal whose action is either to execute a
signal-catching function or to terminate the process. If more than one
thread is suspended in `waitpid()` awaiting termination of the same
process, exactly one thread will return the process status at the time
of the target process termination. If status information is available
prior to the call to `waitpid()`, return will be immediate.
**NOTE**: Because `waitpid()` is not fully POSIX compliant, it must be
specifically enabled by setting `CONFIG_SCHED_WAITPID` in the NuttX
configuration file.
Parameters:
: - **pid** – The task ID of the thread to wait for
- **stat\_loc** – The location to return the exit status
- **options** – `WNOHANG`, `WUNTRACED`, `WCONTINUED` (see below)
The `pid` argument specifies a set of child processes for which status
is requested. The `waitpid()` function will only return the status of
a child process from this set:
- If `pid` is equal to `(pid_t)-1`), status is requested for any
child process. In this respect, `waitpid()` is then equivalent to
`wait()`.
- If `pid` is greater than 0, it specifies the process ID of a single
child process for which status is requested.
- If `pid` is 0, status is requested for any child process whose
process group ID is equal to that of the calling process.
- If `pid` is less than `(pid_t)-1`), status is requested for any
child process whose process group ID is equal to the absolute value
of pid.
The `options` argument is constructed from the bitwise-inclusive OR of
zero or more of the following flags, defined in the `<sys/wait.h>`
header:
- `WCONTINUED`. The `waitpid()` function will report the status of
any continued child process specified by pid whose status has not
been reported since it continued from a job control stop.
- `WNOHANG`. The `waitpid()` function will not suspend execution of
the calling thread if status is not immediately available for one of
the child processes specified by `pid`.
- `WUNTRACED`. The status of any child processes specified by `pid`
that are stopped, and whose status has not yet been reported since
they stopped, will also be reported to the requesting process.
If the calling process has `SA_NOCLDWAIT` set or has `SIGCHLD` set
to `SIG_IGN`, and the process has no unwaited-for children that were
transformed into zombie processes, the calling thread will block until
all of the children of the process containing the calling thread
terminate, and `waitpid()` will fail and set `errno` to `ECHILD`.
If `waitpid()` returns because the status of a child process is
available, these functions will return a value equal to the process ID
of the child process. In this case, if the value of the argument
stat\_loc is not a null pointer, information will be stored in the
location pointed to by `stat_loc`. The value stored at the location
pointed to by `stat_loc` will be 0 if and only if the status returned
is from a terminated child process that terminated by one of the
following means:
1. The process returned 0 from `main()`.
2. The process called `_exit()` or `exit()` with a status argument
of 0.
3. The process was terminated because the last thread in the process
terminated.
Regardless of its value, this information may be interpreted using the
following macros, which are defined in `<sys/wait.h>` and evaluate to
integral expressions; the `stat_val` argument is the integer value
pointed to by `stat_loc`.
- `WIFEXITED(stat_val)`. Evaluates to a non-zero value if status was
returned for a child process that terminated normally.
- `WEXITSTATUS(stat_val)`. If the value of `WIFEXITED(stat_val)` is
non-zero, this macro evaluates to the low-order 8 bits of the status
argument that the child process passed to `_exit()` or `exit()`,
or the value the child process returned from `main()`.
- `WIFSIGNALED(stat_val)`. Evaluates to a non-zero value if status
was returned for a child process that terminated due to the receipt
of a signal that was not caught (see >signal.h<).
- `WTERMSIG(stat_val)`. If the value of `WIFSIGNALED(stat_val)` is
non-zero, this macro evaluates to the number of the signal that
caused the termination of the child process.
- `WIFSTOPPED(stat_val)`. Evaluates to a non-zero value if status was
returned for a child process that is currently stopped.
- `WSTOPSIG(stat_val)`. If the value of `WIFSTOPPED(stat_val)` is
non-zero, this macro evaluates to the number of the signal that
caused the child process to stop.
- `WIFCONTINUED(stat_val)`. Evaluates to a non-zero value if status
was returned for a child process that has continued from a job
control stop.
`<sys/wait.h>` also has `W_EXITCODE(ret, sig)` and
`W_STOPCODE(sig)` (not POSIX, as on other systems).
`W_EXITCODE(ret, 0)` makes the status value of a child process that
exited with the exit status `ret`, and `W_STOPCODE(sig)` the status
value of a child process that the signal `sig` stopped.
Returns:
: If `waitpid()` returns because the status of a child process is
available, it will return a value equal to the process ID of the child
process for which status is reported.
If `waitpid()` returns due to the delivery of a signal to the calling
process, -1 will be returned and `errno` set to `EINTR`.
If `waitpid()` was invoked with WNOHANG set in options, it has at
least one child process specified by pid for which status is not
available, and status is not available for any process specified by pid,
0 is returned.
Otherwise, `(pid_t)-1errno` set to indicate the error:
- `ECHILD`. The process specified by `pid` does not exist or is not
a child of the calling process, or the process group specified by
`pid` does not exist or does not have any member process that is a
child of the calling process.
- `EINTR`. The function was interrupted by a signal. The value of the
location pointed to by `stat_loc` is undefined.
- `EINVAL`. The `options` argument is not valid.
**Assumptions/Limitations:**
**POSIX Compatibility:** Comparable to the POSIX interface of the same
name, but the implementation is incomplete (as detailed above).int waitid(idtype_t idtype, id_t id, FAR siginfo_t *info, int options) : Note
The following discussion is a general description of the `waitid()`
interface. `waitid()` needs `CONFIG_SCHED_HAVE_PARENT`. It
waits for a specific child (`P_PID`), for a child in a process
group (`P_PGID`; an `id` of 0 is the process group of the
caller) or for any child (`P_ALL`), and `SIGCHLD` is used.
`WSTOPPED` and `WCONTINUED` need `CONFIG_SIG_SIGSTOP_ACTION`.
NuttX keeps the status of an exited child only with
`CONFIG_SCHED_CHILD_STATUS`: without it, if `waitid()` is called
after a task has exited, then no status will be available. Options
other than those below, or no `WEXITED`, `WSTOPPED` or
`WCONTINUED`, give `EINVAL`.
The `waitid()` function suspends the calling thread until one child of
the process containing the calling thread changes state. It records the
current state of a child in the structure pointed to by `info`. If a
child process changed state prior to the call to `waitid()`,
`waitid()` returns immediately. If more than one thread is suspended
in `wait()` or `waitpid()` waiting termination of the same process,
exactly one thread will return the process status at the time of the
target process termination
The `idtype` and `id` arguments are used to specify which children
`waitid()` will wait for.
- If `idtype` is P\_PID, `waitid()` will wait for the child with a
process ID equal to (pid\_t)``id``.
- If `idtype` is P\_PGID, `waitid()` will wait for any child with a
process group ID equal to (pid\_t)``id``.
- If `idtype` is P\_ALL, `waitid()` will wait for any children and
`id` is ignored.
The `options` argument is used to specify which state changes
`waitid()` will will wait for. It is formed by OR-ing together one or
more of the following flags:
- `WEXITED`: Wait for processes that have exited.
- `WSTOPPED`: Status will be returned for any child that has stopped
upon receipt of a signal.
- `WCONTINUED`: Status will be returned for any child that was
stopped and has been continued.
- `WNOHANG`: Return immediately if there are no children to wait for.
- `WNOWAIT`: Keep the process whose status is returned in `info` in
a waitable state. This will not affect the state of the process; the
process may be waited for again after this call completes.
The `info` argument must point to a `siginfo_t` structure. If
`waitid()` returns because a child process was found that satisfied
the conditions indicated by the arguments `idtype` and options, then
the structure pointed to by `info` will be filled in by the system
with the status of the process. The `si_signo` member will always be
equal to `SIGCHLD`.
Returns:
: If `waitid()` returns due to the change of state
of one of its children, 0 is returned. Otherwise, -1 is returned and
`errno` is set to indicate the error.
The `waitid()` function will fail if:
- `ECHILD`:
- `EINTR`:
- `EINVAL`: An invalid value was specified for `options`, or
`idtype` and `id` specify an invalid set of processes.
**POSIX Compatibility:** Comparable to the POSIX interface of the same
name, but the implementation is incomplete (as detailed in the
description above).pid_t wait(FAR int *stat_loc) : Note
The following discussion is a general description of the [`wait()`](#c.wait)
interface. However, as of this writing, the implementation of
[`wait()`](#c.wait) is incomplete (but usable). [`wait()`](#c.wait) is based
on [`waitpid()`](#c.waitpid) (see description for further information).
The `wait()` function will suspend execution of the calling thread
until status information for one of its terminated child processes is
available, or until delivery of a signal whose action is either to
execute a signal-catching function or to terminate the process. If more
than one thread is suspended in `wait()` awaiting termination of the
same process, exactly one thread will return the process status at the
time of the target process termination. If status information is
available prior to the call to`wait()`, return will be immediate.
The `waitpid()` function will behave identically to `wait()`, if its
`pid` argument is (pid\_t)-1 and the options argument is 0. Otherwise,
its behavior will be modified by the values of the `pid` and
`options` arguments.
Parameters:
: - **stat\_loc** – The location to return the exit status
Returns:
: See the values returned by [`waitpid()`](#c.waitpid)
**POSIX Compatibility:** Comparable to the POSIX interface of the same
name, but the implementation is incomplete (as detailed in the
description ``waitpaid()` <#waitpid>`\_\_). int atexit(void (*func)(void))
: Registers a function to be called at program exit. The
atexit() function registers the given function to be called at
normal process termination, whether via exit() or via return from
the program’s main().
Note
`CONFIG_LIBC_MAX_EXITFUNS` must be larger than 0 to build
`atexit()`, `on_exit()` and `at_quick_exit()`. A C++ ELF
program (built with `-fno-use-cxa-atexit`) with a static object
calls `atexit()` too, so the default is 1 when both `CONFIG_ELF`
and `CONFIG_HAVE_CXX` are enabled.
The number of functions is limited only by memory: the first
`CONFIG_LIBC_MAX_EXITFUNS` entries are in the task information, the
next ones come from the heap. `atexit()`, `on_exit()`,
`at_quick_exit()` and `__cxa_atexit()` share the list.
Parameters:
: - **func** – A pointer to the function to be called when the task exits.
Returns:
: On success, `atexit()` returns OK (0). On error (no memory),
a non-zero value is returned.
**POSIX Compatibility:** Comparable to the ISO C interface of the same
name. Limitations in the current implementation:
> 1. `atexit()` functions are not inherited when a new task is created. int on_exit(CODE void (*func)(int, FAR void*), FAR void *arg)
: Registers a function to be called at program exit. The
on_exit() function registers the given function to be called at
normal process termination, whether via exit() or via return from
the program’s main(). The function is passed the status argument
given to the last call to exit() and the arg argument from
on_exit().
Note
`CONFIG_LIBC_MAX_EXITFUNS` must be larger than 0 to build
this function.
Parameters:
: - **func** – A pointer to the function to be called when the task exits.
- **arg** – An argument that will be provided to the `on_exit()`
function when the task exits.
Returns:
: On success, `on_exit()` returns OK (0). On error,
ERROR (-1) is returned, and ``errno` <#ErrnoAccess>`\_\_ is set to
indicate the cause of the failure.
**POSIX Compatibility:** This function comes from SunOS 4, but is also
present in libc4, libc5 and glibc. It no longer occurs in Solaris (SunOS
5). Avoid this function, and use the standard `atexit()` instead.
> 1. `on_exit()` shares the list of `atexit()`.
> 2. `on_exit()` functions are not inherited when a new task is created.