Recent from talks
Nothing was collected or created yet.
Nice (Unix)
View on WikipediaThis article needs additional citations for verification. (November 2010) |
| nice | |
|---|---|
| Developer | AT&T Bell Laboratories |
| Initial release | November 1973 |
| Operating system | Unix and Unix-like |
| Platform | Cross-platform |
| Type | Command |
| License | coreutils: GNU GPL v3 4.4BSD: BSD License |
nice is a program found on Unix and Unix-like operating systems such as Linux. It directly maps to a kernel call of the same name. nice is used to invoke a utility or shell script with a particular CPU priority, thus giving the process more or less CPU time than other processes. A niceness of -20 is the lowest niceness, or highest priority. The default niceness for processes is inherited from its parent process and is usually 0.
Systems have diverged on what priority is the lowest. Linux systems document a niceness of 19 as the lowest priority,[1] BSD systems document 20 as the lowest priority.[2] In both cases, the "lowest" priority is documented as running only when nothing else wants to.
Etymology
[edit]Niceness value is a number attached to processes in *nix systems, that is used along with other data (such as the amount of I/O done by each process) by the kernel process scheduler to calculate a process' 'true priority'—which is used to decide how much CPU time is allocated to it.
The program's name, nice, is an allusion to its task of modifying a process' niceness value.
The term niceness itself originates from the idea that a process with a higher niceness value is nicer to other processes in the system and to users by virtue of demanding less CPU power—freeing up processing time and power for the more demanding programs, who would in this case be less nice to the system from a CPU usage perspective.[3]
Use and effect
[edit]nice becomes useful when several processes are demanding more resources than the CPU can provide. In this state, a higher-priority process will get a larger chunk of the CPU time than a lower-priority process. Only the superuser (root) may set the niceness to a lower value (i.e. a higher priority). On Linux it is possible to change /etc/security/limits.conf to allow other users or groups to set low nice values.[4]
If a user wanted to compress a large file without slowing down other processes, they might run the following:
$ nice -n 19 tar cvzf archive.tgz largefile
The exact mathematical effect of setting a particular niceness value for a process depends on the details of how the scheduler is designed on that implementation of Unix. A particular operating system's scheduler will also have various heuristics built into it (e.g. to favor processes that are mostly I/O-bound over processes that are CPU-bound). As a simple example, when two otherwise identical CPU-bound processes are running simultaneously on a single-CPU Linux system, each one's share of the CPU time will be proportional to 20 − p, where p is the process' priority. Thus a process, run with nice +15, will receive 25% of the CPU time allocated to a normal-priority process: (20 − 15)/(20 − 0) = 0.25.[5] On the BSD 4.x scheduler, on the other hand, the ratio in the same example is about ten to one.[citation needed]
Similar commands
[edit]The related renice program can be used to change the priority of a process that is already running.[1]
Linux also has an ionice program, which affects scheduling of I/O rather than CPU time.[6]
See also
[edit]- kill
- ps
- top
- ionice from util-linux (see manual for disk storage I/O priorities)
References
[edit]- ^ a b – Linux General Commands Manual from ManKier.com
- ^ "renice(8) - NetBSD Man Pages". NetBSD. October 22, 2020. Retrieved April 18, 2023.
- ^ Jerry Peek, Shelley Powers, Tim O'Reilly and Mike Loukides (2002). Unix Power Tools. O'Reilly, p. 507.
- ^ – Linux File Formats Manual from ManKier.com
- ^ Silberschatz, Abraham; Galvin, Peter B.; Gagne, Greg (2013). Operating system concepts (ninth ed.). Hoboken, N.J: Wiley. p. 294. ISBN 978-1-118-06333-0.
- ^ – Linux General Commands Manual from ManKier.com
External links
[edit]- : invoke a utility with an altered nice value – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group
Nice (Unix)
View on Grokipedianice() system call, where a higher value indicates lower priority (less favorable scheduling) and a lower value indicates higher priority (more favorable scheduling).[2] In many implementations, such as Linux, the range spans from -20 (highest priority) to +19 (lowest priority), though some, like certain BSD systems, extend to +20, with 0 as the default for processes started without adjustment.[3]
The command's syntax is nice [OPTION] [COMMAND [ARG]... ], where the primary option -n or --adjustment=N specifies the integer increment to add to the current nice value of the invoking process; positive values reduce priority, while negative values increase it, though the latter typically requires superuser privileges to avoid security risks.[1] Exit status reflects the invoked command's result or specific error codes, such as 127 if the command is not found in the PATH.[1]
Defined in the POSIX.1 standard since Issue 4 (1990) and retained in subsequent versions including POSIX.1-2017, nice enables users to manage resource contention by "nicening" low-priority tasks like backups or computations, allowing interactive processes to run more responsively.[1] It is complemented by the renice utility for altering the priority of already running processes and is implemented in core toolsets like GNU Coreutils for Linux and BSD systems.[4] While the exact nice value range is implementation-defined, the default increment is 10, and the command's behavior ensures backward compatibility with historical Unix practices, where it originated as a user-friendly interface to process scheduling.[3]
Introduction
Purpose and Functionality
Thenice command is a command-line utility in Unix-like operating systems that invokes another utility or command with a modified niceness value, thereby altering the CPU scheduling priority of the launched process.[1] This adjustment influences how the operating system's scheduler allocates CPU time among running processes, allowing users to specify a relative priority for the new process at launch time.[1] By default, without an explicit increment, the utility executes with an implementation-defined niceness value that is at least as high as the current process's value, typically resulting in lower priority.[1]
The primary purpose of nice is to facilitate resource management in multitasking environments by enabling the execution of non-urgent or background tasks with reduced CPU access, which helps maintain system responsiveness for foreground or interactive processes.[5] For instance, it allows administrators or users to "nice" computationally intensive jobs, ensuring that critical operations receive preferential treatment without requiring advanced kernel modifications.[3] This mechanism promotes efficient sharing of system resources, particularly in shared or multi-user setups where competing processes could otherwise degrade performance.[1]
As a POSIX-standardized utility, nice is widely available across compliant systems, including Linux distributions, BSD variants such as FreeBSD, and macOS, ensuring consistent behavior in terms of invocation and priority adjustment.[1] [5] It originated in 1973 with Version 4 of AT&T UNIX developed at Bell Labs, as one of the early tools supporting multitasking in the evolving Unix ecosystem.[5] Niceness values generally range from -20 (most favorable scheduling) to 19 (least favorable).[6]
Core Concept of Niceness
In Unix-like operating systems, niceness refers to an integer value that serves as a relative priority indicator for processes, influencing their scheduling by the kernel's CPU allocator. A higher niceness value, such as 19, denotes lower priority, making the process more "nice" by allowing it to receive less CPU time and yield resources more readily to competing processes. Conversely, lower values, including negative ones like -20, signify higher priority, enabling the process to claim more CPU cycles.[1][3] The standard range of niceness values is from -20 (highest priority) to 19 (lowest priority) in Linux implementations, with 0 as the default for newly created processes inherited from the parent. In BSD variants, such as FreeBSD and OpenBSD, the range is similarly -20 to 19 or extends to 20 for the lowest priority, maintaining the default at 0. This scale provides 40 discrete levels, allowing fine-grained adjustments to process favorability without overriding the system's preemptive scheduling.[3][7][8] Conceptually, niceness embodies a principle of courtesy in resource sharing among processes, where higher-niceness tasks are designed to defer execution voluntarily in favor of others during contention for CPU time. This aligns with the cooperative ethos of multitasking in Unix environments, as processes with elevated niceness values are less aggressive in competing for scheduler attention, effectively promoting fairer allocation of system resources. In interaction with the default scheduler, niceness modifies the effective priority used to determine time slice durations—typically shorter for lower-priority (higher-niceness) processes—ensuring that background or less critical tasks do not monopolize the processor.[1][9][10]History
Origins and Development
Thenice command originated in Version 3 of Unix, released in February 1973 by Ken Thompson and Dennis Ritchie at Bell Labs, where it served as a system call to assign low-priority status to processes, supporting the operating system's early multitasking capabilities on PDP-11 hardware.[11] Initially termed "hog" in development, the call—numbered 34 in the system interface—permanently lowered a process's scheduling priority without arguments, aiding resource management in multi-user environments with limited computing power.[11]
Its evolution continued through formal standardization in POSIX.1-1988 (IEEE Std 1003.1), which defined the underlying nice() system interface for portable process priority adjustment across Unix-like systems, promoting interoperability amid diverging commercial variants like System V and BSD.[12] This ensured the command's core behavior—altering niceness values to influence CPU scheduling—remained consistent, with the utility form later detailed in POSIX.2 for shell environments.[1]
Implementations varied post-standardization; Linux adopted nice via the GNU Core Utilities package, with initial components like shellutils emerging around 1991 under David MacKenzie's development, integrating it into distributions from the early 1990s onward for broad compatibility. In contrast, BSD systems, such as FreeBSD, extended the maximum niceness to 20 for the lowest priority, differing from Linux's cap at 19, reflecting subtle kernel scheduling divergences while adhering to POSIX baselines.[7]
As of 2025, the command's core functionality has seen no substantive changes, but its integration with containerization technologies like Docker has grown, allowing niceness adjustments inside containers via the --cap-add=SYS_NICE flag to manage resource contention in isolated environments.[13] Additionally, systemd-based systems have enhanced documentation and support for niceness through unit file directives like Nice=, enabling seamless priority configuration for services without manual invocation.[14]
Etymology
The term "nice" for the Unix command derives from the English adjective meaning courteous or kind, embodying the idea that a process assigned a higher nice value behaves deferentially toward others by reducing its own CPU demands and allowing competing processes more access to system resources. This conceptual linkage highlights how "niceness" promotes cooperative resource sharing in a multi-user environment.[15] In contrast, negative nice values render a process "not nice" by elevating its priority and enabling it to claim more CPU time selfishly at the expense of others, though such adjustments are restricted to privileged users (typically root) to prevent abuse.[1] The name was coined during the 1970s at Bell Labs as part of early Unix development, aligning with the system's philosophy of concise, intuitive naming for utilities to enhance usability and simplicity in process management.[16] Unlike many Unix commands with acronymic or abbreviated origins, "nice" bears no direct etymological connections to other computing terminology and stands unique within the Unix lexicon for process scheduling.[17]Syntax and Usage
Command Syntax
The basic syntax of thenice command follows the form nice [-n increment] [utility [argument...]], where utility optionally specifies the command to execute and argument... provides any required arguments to that command. If no utility is specified, nice writes the current nice value of the invoking process to standard output and exits successfully.[1] This structure conforms to the POSIX.1 standard, ensuring portability across compliant Unix-like systems, though some implementations may vary in exact behavior.[1] In GNU systems, the syntax is equivalently nice [option]... [command [arg]...], supporting long-form options for enhanced usability.[18]
The primary option for specifying the niceness adjustment is -n increment or its long-form equivalent --adjustment=increment, where increment is a positive or negative decimal integer that modifies the priority of the invoked utility relative to the current process.[1][18] This option is mandatory for explicit value control, as omitting it results in a default adjustment. Standard help and version options include -h or --help to display usage information, and -V or --version to show the command's version details; these are part of the GNU Coreutils implementation and enhance scripting portability.[18] An obsolete short form, - increment, was historically used but is deprecated in favor of -n for POSIX compliance.[1][18]
When invoked without an explicit increment, nice defaults to running the specified utility with a niceness value increased by 10 from the current process, lowering its scheduling priority to favor other tasks.[18] Under POSIX guidelines, the default is an implementation-defined value at least as high as the invoking process's niceness, promoting consistent behavior in portable scripts while allowing system-specific optimizations.[1] The niceness values typically range from -20 (highest priority) to 19 (lowest), influencing CPU scheduling without altering real-time guarantees.[18]
Practical Examples
One common practical use of thenice command is to run resource-intensive backup operations at a lower priority to minimize disruption to interactive tasks. For instance, to create a tar archive of the /home directory with an implicit niceness adjustment of +10, the following command can be executed:
nice [tar](/page/Tar) -cf /backup.tar /home
nice [tar](/page/Tar) -cf /backup.tar /home
nice -n 15 make launches the make utility with a niceness of +15 relative to the default, suitable for background compilation on a shared workstation. This adjustment prioritizes interactive processes, enabling smooth multitasking during the build.[19]
Privileged users can employ nice to elevate the priority of time-critical tasks by specifying a negative adjustment, which requires root permissions. For example, sudo nice -n -10 critical_process runs critical_process with a niceness of -10, granting it higher CPU scheduling favor for urgent operations like real-time data processing. Non-root users attempting negative values will encounter a permission denied error.[3]
In batch scripting and automated environments, nice integrates seamlessly with tools like cron to schedule low-priority tasks during off-peak hours. A cron job entry such as 0 2 * * * nice tar -cf /daily_backup.tar /var/log executes a nightly log backup at niceness +10, preventing interference with daytime workloads. After launching, the process's niceness can be verified using ps, where the NI column displays the value; for the above job, ps aux | grep tar might output a line showing NI=10 alongside the process ID.[20][21]
Mechanics and Effects
Priority Adjustment Mechanism
Thenice command adjusts the scheduling priority of a process by invoking the nice() system call or, as a fallback on systems lacking it, the setpriority() system call to modify the niceness value of the current process before executing the target command.[22][23] This adjustment occurs after parsing command-line arguments to determine the niceness increment, which is validated to ensure it falls within permissible bounds.[18] Following the priority adjustment, the command executes the specified program using execvp(), replacing the current process image while preserving the modified niceness value.[22]
In Unix-like systems, the niceness value serves as an offset to a base priority, influencing the process's position in the scheduler's run queue. The effective priority is typically computed as effective_priority = base_priority + nice_value, where the base priority is system-defined (often around 120 for normal processes) and the adjustment factor per niceness unit is 1 in most implementations, though variations exist.[24] For example, in Linux, the static priority maps directly via the macro NICE_TO_PRIO(nice) = MAX_RT_PRIO + 20 + nice, where MAX_RT_PRIO is 100, resulting in priorities from 100 (nice -20) to 139 (nice 19).[25]
Child processes inherit the parent's niceness value upon creation via fork(), unless explicitly altered, ensuring consistent priority propagation across process hierarchies.[26][27]
Platform-specific implementations apply this offset differently in their schedulers. In Linux, the Completely Fair Scheduler (CFS) uses the niceness-derived static priority to assign a weight from a predefined table, where weights approximate , providing a multiplicative share of CPU time (e.g., nice 0 yields weight 1024, while nice 10 yields 320).[24][28] In BSD variants like FreeBSD, the ULE scheduler adjusts time slice sizes inversely proportional to the niceness relative to the lowest-niced runnable thread, with slices ranging from 10 ms (high priority) to 140 ms (low priority) and an overall ratio of approximately 14:1 across the full nice range.[29]
System Impact and Scheduling
The niceness value directly influences a process's share of CPU time in Unix-like systems by adjusting its scheduling weight within the kernel's fair scheduler. In the Completely Fair Scheduler (CFS) and its successor, the Earliest Eligible Virtual Deadline First (EEVDF) scheduler introduced in Linux 6.6, a higher nice value reduces the process's weight, causing its virtual runtime to accumulate faster relative to lower-nice processes. This results in the process receiving proportionally less CPU time; for example, a task with nice 5 receives approximately one-third the CPU execution time of a task with nice 0 (weight ratio 335:1024).[30] Consequently, processes with elevated niceness values execute for shorter effective periods before yielding to others, effectively shrinking their time slices in a fair-sharing model.[31] This mechanism benefits multitasking environments by mitigating the impact of CPU-intensive "hog" processes on system responsiveness. By assigning higher nice values to non-interactive workloads, such as batch jobs or backups, the scheduler ensures that interactive tasks—like user interface updates or shell commands—maintain low virtual runtime and are selected more frequently, preventing starvation in multi-user setups.[30] In practice, this isolation enhances overall system interactivity without requiring complex policy changes, as demonstrated in Linux's handling of SCHED_BATCH tasks alongside normal processes.[32] In modern Linux kernels (6.6 and later as of 2025), EEVDF integrates niceness into virtual deadline calculations similarly to CFS's vruntime approach, weighting tasks to allocate CPU bandwidth fairly while incorporating latency considerations for time slice lengths.[31] No significant alterations to niceness handling have occurred since EEVDF's adoption in late 2023, preserving compatibility with existing tools.[33] However, niceness operates solely within the fair scheduling class (SCHED_NORMAL) and cannot supersede real-time policies like SCHED_FIFO, which preempt fair tasks regardless of nice adjustments to guarantee deterministic execution. This complementary role allows nice to fine-tune fairness among non-real-time workloads without interfering with latency-critical applications.[30]Permissions and Limitations
In Unix-like systems, thenice command imposes strict privilege requirements to ensure fair resource allocation. Non-root users are limited to setting positive niceness values, typically ranging from 0 to 19, which lowers the priority of new processes relative to the default. To specify negative niceness values (increasing priority) or to lower the niceness below the current process's value, elevated privileges are required: root access on traditional Unix systems or the CAP_SYS_NICE Linux capability on modern kernels.[3][2][34][35][36]
This privilege model serves as a security measure, preventing unprivileged users from launching or adjusting processes to high priority, which could otherwise monopolize CPU resources and cause denial-of-service conditions for other users in shared multi-user environments.[2][37]
The nice command has several inherent limitations. It solely adjusts CPU scheduling priority under the default time-sharing policy (e.g., SCHED_OTHER on Linux) and does not influence I/O priority, which must be managed separately using utilities like ionice.[38] Additionally, nice is ineffective for kernel threads, which bypass user-space scheduling, and for processes employing real-time policies such as SCHED_FIFO or SCHED_RR, where priority is governed by distinct real-time values rather than niceness. The command also exerts no control over memory allocation, disk I/O patterns, or other non-CPU resources.
Platform variations exist as of 2025. On FreeBSD, only the superuser can set negative niceness, with no provisions for group-based privileges.[39] In macOS, negative values remain restricted to superuser execution, but for processes launched via launchd, the Nice key in the plist file allows priority specification (range -20 to 20); however, negative settings necessitate that the job run with root privileges to comply with system security constraints.[36][40]
Related Commands
Renice
Therenice command is a Unix utility that modifies the scheduling priority, or "niceness," of one or more already running processes, allowing dynamic adjustments without requiring process termination or restart.[41] Unlike the nice command, which sets priorities for newly invoked processes, renice targets existing ones identified by process ID (PID), process group ID, or user, making it essential for runtime resource management in multi-user environments.[42] It operates within the same niceness scale as nice, typically ranging from -20 (highest priority) to 19 (lowest), where higher niceness values yield to other processes during CPU scheduling.[41]
The standard syntax, as defined in POSIX, is renice [-g|-p|-u] -n increment ID..., where -n increment specifies a relative adjustment to the current nice value (positive increments lower priority, negative ones raise it and often require superuser privileges), and ID represents the target identifiers.[41] The -p option (default) treats operands as PIDs, -g as process group IDs affecting all processes in the group, and -u as user names or IDs affecting all processes owned by the user.[41] Many implementations, such as those in Linux, extend this to support absolute priority values without the -n flag or with options like --priority, though POSIX compliance requires relative increments when POSIXLY_CORRECT is set in the environment.[42]
In terms of functionality, renice alters the nice value immediately upon invocation, influencing the process scheduler's decisions without interrupting execution, but changes are bounded by system limits and effective user privileges.[41] Ordinary users can only increase the nice value (deprioritize) their own processes, a restriction enforced to prevent resource hogging, while superusers (root) can set any value, including decreases for higher priority.[42] This privilege model ensures fairness, as non-privileged attempts to lower nice values (raise priority) fail with an error, though since Linux kernel 2.6.12, such operations may be allowed if within per-user resource limits configured via tools like ulimit.[42]
Common use cases include dynamically tuning long-running, CPU-intensive tasks to prevent system slowdowns, such as deprioritizing a compilation job with renice +10 -p 1234 (where 1234 is the PID), which adds 10 to its nice value and reduces its CPU share in favor of interactive processes.[42] Administrators might use it to prioritize critical services, like renice -5 -u postgres to slightly elevate all PostgreSQL processes owned by the postgres user, provided they have root access.[41]
Introduced in 4.0BSD and later standardized in POSIX.1-2001 (IEEE Std 1003.1), renice differs fundamentally from nice by operating on running processes via explicit identifiers rather than launching new ones, enabling finer control in ongoing system operations.[42][41] This design supports the shared niceness value system across Unix-like operating systems, where adjustments propagate to the scheduler without affecting process state otherwise.[41]
Ionice and Other Utilities
ionice is a Linux-specific utility that sets or retrieves the I/O scheduling class and priority for a process or program. Introduced in Linux kernel 2.6.13 (November 2005), it was designed to provide fine-grained control over disk I/O resource allocation, addressing the need to prioritize I/O operations separately from CPU scheduling and helping to prevent I/O-intensive tasks from overwhelming system disk access. However, its effectiveness depends on the underlying I/O scheduler; it was primarily supported by the CFQ scheduler, which was deprecated in kernel 5.0 (2019) and removed from mainline kernels thereafter. In modern Linux kernels (as of November 2025), default multi-queue schedulers like mq-deadline or none do not enforce I/O priorities set by ionice, rendering the tool ineffective for priority control in standard configurations unless a compatible scheduler such as BFQ (an optional, out-of-tree or distribution-provided alternative) is enabled. For comprehensive I/O management in contemporary systems, tools like cgroups v2 with io.weight are recommended for throttling and prioritization.[38][43][44]
The syntax of ionice allows specification of the scheduling class using the -c option, with three available classes: real-time (1), best-effort (2), and idle (3).[38] Within the best-effort and real-time classes, a niceness value from 0 (highest priority) to 7 (lowest) can be set using the -n option, while the idle class does not accept a priority argument as it only permits I/O when the disk is otherwise idle.[38] For example, to run a command with idle I/O priority, one would use ionice -c 3 command, ensuring the process yields disk access to others unless no other activity is present.[45] This complements the nice command by providing I/O-specific adjustments where supported, allowing for more comprehensive resource management across CPU and disk subsystems.[38]
Beyond I/O priorities, several related utilities facilitate broader process resource control in Unix-like systems. The chrt command sets or retrieves real-time scheduling attributes for processes, supporting policies such as SCHED_FIFO (first-in, first-out) and SCHED_RR (round-robin) to enable low-latency CPU execution for time-critical tasks.[46] Similarly, taskset retrieves or sets the CPU affinity of a process, restricting it to specific cores or processors to optimize performance on multi-core systems; for instance, taskset -c 0-3 command binds the command to the first four CPUs.[47] The nohup command, meanwhile, runs a process immune to hangup (SIGHUP) signals, allowing it to persist in the background after terminal logout or disconnection, and it is commonly paired with nice for low-priority long-running jobs without altering the priority itself.[48]