fbpx

Comandos Linux – Comando top

Comando top do Linux

comando top

No Unix-like sistemas operacionais, o topo programa fornece uma visão em tempo real dinâmica de um sistema em execução. Ele pode exibir informações de resumo do sistema, bem como uma lista de processos ou threads actualmente a ser geridos pelo núcleo . Os tipos de informações de resumo do sistema mostrados e os tipos, ordem e tamanho das informações exibidas para tarefas são todos configuráveis ​​pelo usuário.

Este documento cobre a versão Linux do top .

Sintaxe

top -hv | -bcHisS -d atraso -n limite -u | U usuário | -p pid -w [ cols ]

Opções

NotaAs opções tipicamente obrigatórias (‘  ‘) e até espaços em branco são completamente opcionais.

-h -vAjuda / Versão

Mostre a versão da biblioteca e o prompt de uso e saia.

-bOperação no modo

em lote Inicia no topo no modo ‘Lote’, o que pode ser útil para enviar a saída do topo para outros programas ou para um arquivo. Nesse modo, o top não aceita entrada e é executado até o limite de iterações que você definiu com a opção de linha de comando ‘ -n ‘ ou até que seja eliminado.

-cAlternar linha de comando / nome do programa

Inicia o topo com o último estado ‘ c ‘ lembrado invertido. Portanto, se top estava exibindo linhas de comando, agora esse campo mostrará os nomes dos programas e vice-versa. Veja o comando interativo ‘ c ‘ para informações adicionais.

intervalo -dTempo de atraso , em que o intervalo é representado como: ss.tt ( segundos . décimos)

Especifica o atraso entre as atualizações de tela e substitui o valor correspondente no arquivo de configuração pessoal ou no padrão de inicialização. Posteriormente, isso pode ser alterado com os comandos interativos ‘ d ‘ ou ‘ s ‘.

Os segundos fracionários são respeitados, mas um número negativo não é permitido. Em todos os casos, no entanto, essas alterações são proibidas se top estiver em execução no ‘Modo seguro’, exceto no root (a menos que a opção de linha de comando ‘ s ‘ tenha sido usada).

-HOperação no modo de threads

Instrui top para exibir threads individuais. Sem essa opção de linha de comando, é mostrada uma soma de todos os threads em cada processo. Posteriormente, isso pode ser alterado com o comando interativo ‘ H ‘.

-EuAlternar processo ocioso

Inicia o topo com o último estado ‘ i ‘ lembrado invertido. Quando essa opção está Desativada, as tarefas que não usaram nenhuma CPU desde a última atualização não serão exibidas.

-n limiteNúmero de iterações

Especifica o número máximo de iterações, ou quadros, que a parte superior deve produzir antes de terminar.

-p pidModo Monitor-PIDs , especificado como: -p pid1 -p pid2 … ou -p pid1, pid2, pid3 …

Monitora apenas processos com IDs de processo especificados. Essa opção pode ser fornecida até 20 vezes ou você pode fornecer uma lista delimitada por vírgula com até 20 pids. É permitida a combinação de ambas as formas.

Um valor pid igual a zero será tratado como o ID do processo do próprio programa superior (uma vez em execução).

Somente esta opção de linha de comando e, se você desejar retornar à operação normal, não é necessário sair e reiniciar o topo – basta emitir qualquer um destes comandos interativos: ‘ = ‘, ‘ u ‘ ou ‘ U ‘.

O ‘ p ‘, ‘As opções de linha de comando u ‘e’ U ‘são mutuamente exclusivas.

-sOperação em modo seguro

Inicia no topo com o modo seguro forçado, mesmo para raiz. Esse modo é muito melhor controlado pelo arquivo de configuração do sistema (consulte o tópico 6. ARQUIVOS).

-SAlternância de tempo cumulativo

Inicia o topo com o último estado ‘ S ‘ lembrado invertido. Quando o modo ‘Tempo acumulado’ está Ativado , cada processo é listado com o tempo da CPU que ele e seus filhos mortos usaram. Consulte o comando interativo ‘ S ‘ para obter informações adicionais sobre este modo.

-u | -U ID-do-usuário ou nomeModo de filtro de usuário A

exibição apenas processa com um ID ou nome de usuário correspondente ao fornecido. A opção ‘ -u ‘ corresponde ao usuário efetivo, enquanto a opção ‘ -U ‘ corresponde a qualquer usuário (real, efetivo, salvo ou sistema de arquivos).

As opções de linha de comando ‘ p ‘, ‘ u ‘ e ‘ U ‘ são mutuamente exclusivas.

-w númeroSubstituição da largura de saída

No modo ‘Lote’, quando usado sem um argumento superior, formatará a saída usando as variáveis ​​de ambiente COLUMNS = e LINES =, se configuradas. Caso contrário, a largura será fixada no máximo 512 colunas. Com um argumento, a largura da saída pode ser reduzida ou aumentada (até 512), mas o número de linhas é considerado ilimitado.

No modo de exibição normal, quando usado sem um argumento, o topo tentará formatar a saída usando as variáveis ​​de ambiente COLUMNS = e LINES =, se configuradas. Com um argumento, a largura da saída pode ser reduzida apenas, não aumentada. Seja usando variáveis ​​de ambiente ou um argumento com -w, quando não estiver no modo ‘Lote’, as dimensões reais do terminal nunca poderão ser excedidas.

Nota: Sem o uso desta opção de linha de comando, a largura da saída sempre é baseada no terminal no qual o topo foi chamado, seja no modo ‘Lote’.

Exibição de resumo

Cada uma das seguintes áreas é controlada individualmente por meio de comandos interativos.

Médias de tempo de atividade e carga

Esta seção consiste em uma única linha exibindo o seguinte:

  • nome do programa ou da janela, dependendo do modo de exibição
  • hora atual e tempo desde a última inicialização
  • número total de usuários
  • média de carregamento do sistema nos últimos 1, 5 e 15 minutos

Estados da tarefa e da CPU

Esta seção consiste em no mínimo duas linhas. Em um ambiente SMP, linhas adicionais podem refletir porcentagens individuais de estado da CPU.

  • A linha 1 mostra o total de tarefas ou threads, dependendo do estado da alternância no modo Threads. Esse total é ainda classificado como: corrida ; dormindo ; parou ; zumbi
  • A linha 2 mostra as porcentagens de estado da CPU com base no intervalo desde a última atualização. Onde dois rótulos são mostrados abaixo, os das versões mais recentes do kernel são mostrados primeiro:us, user : tempo executando processos un-niced de usuário
    sy, sistema : tempo executando processos nernel
    ni, nice : tempo executando processos de usuário niced
    wa, IO-wait : tempo aguardando a conclusão da E / S
    oi : tempo gasto em manutenção de hardware interrompe
    si : tempo gasto em manutenção de software interrompe
    st : tempo roubado desta VM pelo hypervisor

Uso de memória

Essa parte consiste em duas linhas que podem expressar valores em kibibytes (KiB), mebibytes (MiB) ou gibibytes (GiB), dependendo da quantidade de memória física .

  • Line 1 reflects physical memory, classified as: totalusedfreebuffers
  • Line 2 reflects virtual memory, classified as: totalusedfreecached

Fields / Columns

Listed below are top’s available process fields (columns). They are shown in alphabetical order. You may customize their position and whether or not they are displayable with the ‘f‘ or ‘F‘ (Fields Management) interactive commands.

Any field is selectable as the sort field, and you control whether they are sorted high-to-low or low-to-high.

CGROUPS — Control Groups

The names of the control group(s) to which a process belongs, or ‘‘ if not applicable for that process.

Control Groups provide for allocating resources (cpu, memory, network bandwidth, etc.) among installation-defined groups of processes. They enable fine-grained control over allocating, denying, prioritizing, managing and monitoring those resources.

Many different hierarchies of “cgroups” can exist simultaneously on a system and each hierarchy is attached to one or more subsystems. A subsystem represents a single resource.

NoteThe ‘CGROUPS’ field, unlike most columns, is not fixed-width. When displayed, it plus any other variable width columns will be allocated all remaining screen width (up to the maximum 512 characters).

  1. CODE — Code Size (KiB). The amount of physical memory devoted to executable code, also known as the ‘text resident set’ size or TRS.
  2. COMANDO – Nome ou linha de comando. Exiba a linha de comando usada para iniciar uma tarefa ou o nome do programa associado. Você alterna entre linha de comando e nome com ‘ c ‘, que é uma opção de linha de comando e um comando interativo. Quando você escolhe exibir as linhas de comando, os processos sem uma linha de comando (como os threads do kernel) serão mostrados apenas com o nome do programa entre colchetes (por exemplo: ” [mrecoveryd] “). Qualquer forma de exibição está sujeita a truncamento em potencial se for muito longo para caber na largura atual desse campo. Essa largura depende de outros campos selecionados, sua ordem e a largura atual da tela. Este campo também pode ser afetado pelo modo de exibição ‘forest view’. Veja o ‘ V‘comando interativo para obter informações adicionais sobre esse modo.Nota: O campo ‘COMMAND’, diferente da maioria das colunas, não tem largura fixa. Quando exibido, mais qualquer outra coluna de largura variável será alocada em toda a largura restante da tela (até o máximo de 512 caracteres).
  3. % CPU – Uso da CPU. O compartilhamento da tarefa do tempo decorrido da CPU desde a última atualização da tela, expresso como uma porcentagem do tempo total da CPU. Em um ambiente SMP verdadeiro, se o ‘Modo Irix’ estiver Desativado, a parte superior funcionará no ‘Modo Solaris’, onde o uso da CPU da tarefa será dividido pelo número total de CPUs. Você alterna os modos ‘Irix / Solaris’ com o comando interativo ‘ I ‘.
  4. DADOS – Dados + tamanho da pilha (KiB). A quantidade de memória física dedicada a outro código que não o executável, também conhecido como tamanho do ‘conjunto de residentes de dados’ ou DRS.
  5. Sinalizadores – Sinalizadores de tarefas. Esta coluna representa os sinalizadores de agendamento atuais da tarefa que são expressos em notação hexadecimal e com zeros suprimidos. Esses sinalizadores são oficialmente documentados em <linux / sched.h>.
  6. GID – ID do grupo O ID do grupo efetivo.
  7. GRUPO – Nome do grupo. O nome do grupo efetivo.
  8. % MEM – Uso de Memória (RES). O compartilhamento atualmente usado de uma tarefa da memória física disponível.
  9. NI – Nice Value. O bom valor da tarefa. Um valor bom negativo significa prioridade mais alta, enquanto um valor bom positivo significa prioridade mais baixa. Zero neste campo significa que a prioridade não será ajustada na determinação da indisponibilidade de uma tarefa.
  10. nDRT – Contagem de páginas sujas. O número de páginas que foram modificadas desde a última gravação no armazenamento auxiliar. As páginas sujas devem ser gravadas no armazenamento auxiliar antes que o local da memória física correspondente possa ser usado para alguma outra página virtual.
  11. nMaj – Contagem de falhas de página principal. O número de falhas principais de página que ocorreram para uma tarefa. Uma falha de página ocorre quando um processo tenta ler ou gravar em uma página virtual que não está presente no espaço de endereço. Uma falha grave na página ocorre quando o acesso ao armazenamento auxiliar está envolvido na disponibilização dessa página.
  12. nMin – Contagem secundária de falhas de página. O número de falhas secundárias de página que ocorreram para uma tarefa. Uma falha de página ocorre quando um processo tenta ler ou gravar em uma página virtual que não está presente no espaço de endereço. Uma falha menor na página não envolve acesso auxiliar ao armazenamento para disponibilizar essa página.
  13. nTH – Número de threads. O número de threads associados a um processo.
  14. P – Última CPU usada (SMP). Um número que representa o último processador usado. Em um ambiente SMP verdadeiro, isso provavelmente mudará frequentemente, pois o kernel usa intencionalmente uma afinidade fraca. Além disso, o próprio ato de execução pode quebrar essa afinidade fraca e fazer com que mais processos alterem as CPUs com mais frequência (devido à demanda extra por tempo de CPU).
  15. PGRP – ID do grupo de processos. Todo processo é membro de um grupo de processos exclusivo usado para distribuição de sinais e por terminais para arbitrar solicitações de entrada e saída. Quando um processo é criado (bifurcado), ele se torna um membro do grupo de processos de seu pai. Por convenção, esse valor é igual ao ID do processo (consulte PID) do primeiro membro de um grupo de processos, chamado líder do grupo de processos.
  16. PID – ID do processo. O ID do processo exclusivo da tarefa, que periodicamente é encerrado, embora nunca seja reiniciado em zero. Em termos de kernel, é uma entidade despachável definida por uma ‘task_struct’.Este valor também pode ser usado como: um ID do grupo de processos (consulte PGRP); um ID de sessão para o líder da sessão (consulte SID); um ID do grupo de encadeamentos para o líder do grupo de encadeamentos (consulte TGID); e um ID do grupo de processos TTY para o líder do grupo de processos (consulte TPGID).
  17. PPID – ID do processo pai. O ID do processo (pid) do pai de uma tarefa.
  18. PR – Prioridade. A prioridade de agendamento da tarefa. Se você ver ‘rt’ neste campo, significa que a tarefa está sendo executada sob a prioridade de agendamento ’em tempo real’.No linux, a prioridade em tempo real é um tanto enganadora, pois tradicionalmente o próprio funcionamento não era preemptivo. E, embora o kernel 2.6 possa ser preemptivo, nem sempre é assim.
  19. RES – Tamanho da Memória do Residente (KiB). A memória física não trocada que uma tarefa usou.
  20. RUID – ID do usuário real.
  21. RUSER – Nome de usuário real.
  22. S – Status do processo. O estado da tarefa que pode ser um de:’ D ‘ = sono ininterrupta
    ‘ R ‘ = executando
    ‘ S = dormir’
    ‘ T ‘ = rastreada ou parado
    ‘ Z ‘ = zombietarefas apresentadas como correr deve ser mais correctamente considerado como ‘ready to run’ – sua task_struct é representada na fila de execução do Linux. Mesmo sem uma verdadeira máquina SMP, você poderá ver inúmeras tarefas nesse estado, dependendo do intervalo de atraso e do valor agradável da parte superior.
  23. SHR – Tamanho da memória compartilhada (KiB). A quantidade de memória compartilhada disponível para uma tarefa, que geralmente não é totalmente residente. Ele reflete a memória que pode ser potencialmente compartilhada com outros processos.
  24. SID – ID da sessão. Uma sessão é uma coleção de grupos de processos (consulte PGRP), geralmente estabelecidos pelo shell de logon. Um processo recém-bifurcado ingressa na sessão de seu criador. Por convenção, esse valor é igual ao ID do processo (consulte PID) do primeiro membro da sessão, chamado líder da sessão, que geralmente é o shell de logon.
  25. SUID – ID do usuário salvo. O ID do usuário salvo.
  26. SUPGIDS – IDs de grupo suplementares. Os IDs de qualquer grupo suplementar estabelecido no logon ou herdado do pai de uma tarefa. Eles são exibidos em uma lista delimitada por vírgula.Nota: O campo ‘SUPGIDS’, diferente da maioria das colunas, não tem largura fixa. Quando exibido, mais qualquer outra coluna de largura variável será alocada em toda a largura restante da tela (até o máximo de 512 caracteres).
  27. SUPGRPS – Nomes de Grupos Suplementares. Os nomes de qualquer grupo suplementar estabelecido no logon ou herdado do pai da tarefa. Eles são exibidos em uma lista delimitada por vírgula.Nota: O campo ‘SUPGRPS’, diferente da maioria das colunas, não tem largura fixa. Quando exibido, mais qualquer outra coluna de largura variável será alocada em toda a largura restante da tela (até o máximo de 512 caracteres).
  28. SUSER — Saved User Name. The saved user name.
  29. SWAP — Swapped Size (KiB). The non-resident portion of a task’s address space.
  30. TGID — Thread Group Id. The ID of the thread group to which a task belongs. It is the PID of the thread group leader. In kernel terms, it represents those tasks that share an ‘mm_struct’.
  31. TIME — CPU Time. Total CPU time the task has used since it started. When ‘Cumulative mode’ is On, each process is listed with the cpu time that it and its dead children have used. You toggle ‘Cumulative mode’ with ‘S‘, which is both a command-line option and an interactive command. See the ‘S‘ interactive command for additional information regarding this mode.
  32. TIME+ — CPU Time (hundredths). The same as ‘TIME’, but reflecting more granularity through hundredths of a second.
  33. TPGID — Tty Process Group Id. The process group ID of the foreground process for the connected tty, or -1 if a process is not connected to a terminal. By convention, this value equals the process ID (see PID) of the process group leader (see PGRP).
  34. TTY — Controlling Tty. The name of the controlling terminal. The TTY is usually the device (serial port, pty, etc.) from which the process was started, and which it uses for input or output. However, a task need not be associated with a terminal, in which case you’ll see ‘?‘ displayed.
  35. UID — User Id. The effective user ID of the task’s owner.
  36. USER — User Name. The effective user name of the task’s owner.
  37. VIRT — Virtual Memory Size (KiB). The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.
  38. WCHAN — Sleeping in Function. Depending on the availability of the kernel link map (‘System.map’), this field shows the name or the address of the kernel function in which the task is currently sleeping. Running tasks displays a dash (‘‘) in this column.By displaying this field, top’s own working set could be increased by over 700 Kb, depending on the kernel version. Should that occur, your only means of reducing that overhead will be to stop and restart top.Note: The ‘WCHAN’ field, unlike most columns, is not fixed-width. When displayed, it plus any other variable width columns will be allocated all remaining screen width (up to the maximum 512 characters).

Managing Fields

After pressing the interactive command ‘f‘ or ‘F‘ (Fields Management) you will be presented with a screen showing: 1) the ´current´ window name; 2) the designated sort field; 3) all fields in their current order along with descriptions. Entries marked with an asterisk are the currently displayed fields, screen width permitting.

  • As the on-screen instructions indicate, you navigate among the fields with the Up and Down arrow keys. The PgUp, PgDn, Home and End keys can also be used to quickly reach the first or last available field.
  • The Right arrow key selects a field for repositioning and the Left arrow key or the <Enter> key commits that field’s placement.
  • The ‘d‘ key or the <Space> bar toggles a field’s display status, and thus the presence or absence of the asterisk.
  • The ‘s‘ key designates a field as the sort field. See topic 4c. TASK AREA Commands, SORTING for additional information regarding your selection of a sort field.
  • The ‘a‘ and ‘w‘ keys can be used to cycle through all available windows and the ‘q‘ or <Esc> keys exit Fields Management.

The Fields Management screen can also be used to change the ´current´ window/field group in either full-screen mode or alternate-display mode. Whatever was targeted when ‘q‘ or <Esc> was pressed will be made current as you return to the top display. See topic 5. ALTERNATE-DISPLAY Provisions and the ‘g‘ interactive command for insight into ´current´ windows and field groups.

Note: Any window that has been scrolled horizontally will be reset if any field changes are made via the Fields Management screen. Any vertical scrolled position, however, will not be affected. See topic 5c. SCROLLING a Window for additional information regarding vertical and horizontal scrolling.

Interactive Commands

Listed below is a brief index of commands within categories. Some commands appear more than once — their meaning or scope may vary depending on the context in which they are issued.

Global Commands

The global interactive commands are always available in both full-screen mode and alternate-display mode. However, some of these interactive commands are not available when running in ‘Secure mode’.

If you want to know in advance whether or not your top has been secured, ask for help and view the system summary on the second line.

<Enter> or <Space>Refresh-Display

These commands awaken top and following receipt of any input the entire display will be repainted. They also force an update of any hotplugged cpu or physical memory changes.

Use either of these keys if you have a large delay interval and wish to see current status.

? or hHelp

There are two help levels available. The first will provide a reminder of all the basic interactive commands. If top is secured, that screen will be abbreviated.

Typing ‘h‘ or ‘?‘ on that help screen will take you to help for those interactive commands applicable to alternate-display mode.

=Exit-Task-Limits

Removes restrictions on which tasks are shown. This command will reverse any ‘i‘ (idle tasks) and ‘n‘ (max tasks) commands that might be active. It also provides for an ‘exit’ from pid monitoring and user filtering. See the ‘-p‘ command-line option for a discussion of PID monitoring and the ‘U‘ or ‘u‘ interactive commands regarding user filtering.

Additionally, any window that has been scrolled will be reset with this command.

AAlternate-Display-Mode toggle

This command will switch between full-screen mode and alternate-display mode.

BBold-Disable/Enable toggle

This command will influence use of the ‘bold’ terminfo capability and alters both the summary area and task area for the ´current´ window. While it is intended primarily for use with dumb terminals, it can be applied anytime.

Note: When this toggle is On and top is operating in monochrome mode, the entire display will appear as normal text. Thus, unless the ‘x‘ or ‘y‘ toggles are using reverse for emphasis, there will be no visual confirmation that they are even on.

d or sChange-Delay-Time-interval

You will be prompted to enter the delay time, in seconds, between display updates.

Fractional seconds are honored, but a negative number is not allowed. Entering 0 causes (nearly) continuous updates, with an unsatisfactory display as the system and tty driver try to keep up with top’s demands. The delay value is inversely proportional to system loading, so set it with care.

If at any time you want to know the current delay time, ask for help and view the system summary on the second line.

gChoose-Another-Window/Field-Group

You will be prompted to enter a number between 1 and 4 designating the field group which should be made the ´current´ window. You will soon grow comfortable with these 4 windows, especially after experimenting with alternate-display mode.

HThreads-mode toggle

When this toggle is On, individual threads will be displayed for all processes in all visible task windows. Otherwise, top displays a summation of all threads in each process.

IIrix/Solaris-Mode toggle

When operating in ‘Solaris mode’ (‘I‘ toggled Off), a task’s cpu usage will be divided by the total number of CPUs. After issuing this command, you’ll be told the new state of this toggle.

kKill-a-task

You will be prompted for a PID and then the signal to send. The default signal, as reflected in the prompt, is SIGTERM. However, you can send any signal, via number or name.

If you want to abort the kill process, do one of the following depending on your progress:

1) at the pid prompt, just press <Enter>

2) at the signal prompt, type 0

qQuit
rRenice-a-Task

You will be prompted for a PID and then the value to nice. Entering a positive value will cause a process to lose priority. Conversely, a negative value will cause a process to be viewed more favorably by the kernel.

WWrite-the-Configuration-File

This key saves all of your options and toggles plus the current display mode and delay time. By issuing this command just before quitting top, you will be able restart later in exactly that same state.

ZChange-Color-Mapping

This key takes you to a separate screen where you can change the colors for the ´current´ window, or for all windows. For details regarding this interactive command see topic 4d. COLOR Mapping.

* The commands shown with an asterisk (´*´) are not available in ‘Secure mode’, nor will they be shown on the level-1 help screen.

Summary Area Commands

The summary area interactive commands are always available in both full-screen mode and alternate-display mode. They affect the beginning lines of your display and will determine the position of messages and prompts.

These commands always impact just the ´current´ window/field group. See topic 5. ALTERNATE-DISPLAY Provisions and the ‘g‘ interactive command for insight into ´current´ windows and field groups.

lLoad-Average/Uptime toggle

This command is also the line containing the program name (possibly an alias) when operating in full-screen mode or the ´current´ window name when operating in alternate-display mode.

tTask/Cpu-States toggle

This command affects from 2 to many summary area lines, depending on the state of the ‘1‘ toggle and whether or not top is running under true SMP.

This portion of the summary area is also influenced by the ‘H‘ interactive command toggle, as reflected in the total label which shows either ‘Tasks’ or ‘Threads’.

1Single/Separate-Cpu-States toggle

This command affects how the ‘t‘ command’s Cpu States portion is shown. Although this toggle exists primarily to serve massively-parallel SMP machines, it is not restricted to solely SMP environments.

When you see ‘%Cpu(s):’ in the summary area, the ‘1‘ toggle is On and all cpu information is gathered in a single line. Otherwise, each cpu is displayed separately as: ‘%Cpu0, %Cpu1, …’ up to available screen height.

mMemory/Swap-Usage toggle

This command affects the two summary area lines dealing with physical and virtual memory.

Note: If the entire summary area has been toggled Off for any window, you would be left with just the message line. In that way, you will have maximized available task rows but (temporarily) sacrificed the program name in full-screen mode or the ´current´ window name when in alternate-display mode.

Task Area Commands

The task area interactive commands are always available in full-screen mode.

The task area interactive commands are never available in alternate-display mode if the ´current´ window’s task display has been toggled Off (see topic 5. ALTERNATE-DISPLAY Provisions).

Appearance Of Task Window

The following commands will also be influenced by the state of the global ‘B‘ (bold enable) toggle.

bBold/Reverse toggle

This command will impact how the ‘x‘ and ‘y‘ toggles are displayed. Further, it will only be available when at least one of those toggles is On.

xColumn-Highlight toggle

Changes highlighting for the current sort field. If you forget which field is being sorted this command can serve as a quick visual reminder, providing the sort field is being displayed. The sort field might not be visible because:

1) there is insufficient Screen Width

2) the ‘f‘ interactive command turned it Off

yRow-Highlight toggle

Changes highlighting for “running” tasks. Use of this provision provides important insight into your system’s health. The only costs will be a few additional tty escape sequences.

zColor/Monochrome toggle

Switches the ´current´ window between your last used color scheme and the older form of black-on-white or white-on-black. This command will alter both the summary area and task area but does not affect the state of the ‘x‘, ‘y‘ or ‘b‘ toggles.

Content Of Task Window

cCommand-Line/Program-Name toggle

This command will be honored whether or not the ‘COMMAND’ column is currently visible. Later, should that field come into view, the change you applied will be seen.

f or FFields-Management

These keys display a separate screen where you can change which fields are displayed, their order and also designate the sort field.

SCumulative-Time-Mode toggle

When ‘Cumulative mode’ is On, each process is listed with the cpu time that it and its dead children have used.

When Off, programs that fork into many separate tasks will appear less demanding. For programs like ‘init’ or a shell this is appropriate but for others, like compilers, perhaps not. Experiment with two task windows sharing the same sort field but with different ‘S‘ states and see which representation you prefer.

After issuing this command, you’ll be informed of the new state of this toggle. If you want to know in advance whether or not ‘Cumulative mode’ is in effect, ask for help and view the window summary on the second line.

u or UShow-Specific-User-Only

You will be prompted for the uid or name of the user to display. The ‘-u‘ option matches on effective user whereas the ‘-U‘ option matches on any user (real, effective, saved, or filesystem).

Thereafter, in that task window only matching users will be shown, or possibly no processes will be shown. Different task windows can be used to filter different users.

Later, if you want to monitor all tasks again in the ´current´ window, re-issue this command but just press <Enter> at the prompt.

VForest-View-Mode toggle

In this mode, processes are reordered according to their parents and the layout of the COMMAND column resembles that of a tree. In forest view mode it is still possible to toggle between program name and command line (see the ‘c‘ interactive command) or between processes and threads (see the ‘H‘ interactive command).

Note: Typing any key affecting the sort order will exit forest view mode in the ´current´ window. See topic 4c. TASK AREA Commands, SORTING for information on those keys.

Size Of Task Window

iIdle-Process toggle

Displays all tasks or just active tasks. When this toggle is Off, tasks that have not used any CPU since the last update will not be displayed. However, due to the granularity of the %CPU and TIME+ fields, some processes may still be displayed that appear to have used no CPU.

If this command is applied to the last task display when in alternate-display mode, then it will not affect the window’s size, as all prior task displays will have already been painted.

n or #Set-Maximum-Tasks

You will be prompted to enter the number of tasks to display. The lessor of your number and available screen rows will be used.

When used in alternate-display mode, this is the command that gives you precise control over the size of each currently visible task display, except for the very last. It will not affect the last window’s size, as all prior task displays will have already been painted.

Note: If you want to increase the size of the last visible task display when in alternate-display mode, decrease the size of the task display(s) above it.

Sorting Of Task Window

For compatibility, this top supports most of the former top sort keys. Since this is primarily a service to former top users, these commands do not appear on any help screen.

commandsorted-fieldsupported
Astart time (non-display)No
M%MEMYes
NPIDYes
P%CPUYes
TTIME+Yes

Before using any of the following sort provisions, top suggests that you temporarily turn on column highlighting using the ‘x‘ interactive command. That will help ensure that the actual sort environment matches your intent.

The following interactive commands will only be honored when the current sort field is visible. The sort field might not be visible because:

1) there is insufficient Screen Width
2) the ‘f‘ interactive command turned it Off

<Move-Sort-Field-Left

Moves the sort column to the left unless the current sort field is the first field being displayed.

>Move-Sort-Field-Right

Moves the sort column to the right unless the current sort field is the last field being displayed.

The following interactive commands will always be honored whether or not the current sort field is visible.

f or FFields-Management

These keys display a separate screen where you can change which field is used as the sort column, among other functions. This command can be a convenient way to verify the current sort field, when running top with column highlighting turned Off.

RReverse/Normal-Sort-Field toggle

Using this interactive command you can alternate between high-to-low and low-to-high sorts.

NoteField sorting uses internal values, not those in column display. Thus, the TTY and WCHAN fields will violate strict ASCII collating sequence.

Alternate-Display Provisions: Microsoft Windows

Field Groups/Windows

In full-screen mode there is a single window represented by the entire screen. That single window can still be changed to display 1 of 4 different field groups (see the ‘g‘ interactive command, repeated below). Each of the 4 field groups has a unique separately configurable summary area and its own configurable task area.

In alternate-display mode, those 4 underlying field groups can now be made visible simultaneously, or can be turned Off individually at your command.

The summary area will always exist, even if it’s only the message line. At any given time only one summary area can be displayed. However, depending on your commands, there could be from zero to four separate task displays currently showing on the screen.

Current Window

The ´current´ window is the window associated with the summary area and the window to which task related commands are always directed. Since in alternate-display mode you can toggle the task display Off, some commands might be restricted for the ´current´ window.

A further complication arises when you have toggled the first summary area line Off. With the loss of the window name (the ‘l‘ toggled line), you’ll not easily know what window is the ´current´ window.

Commands for Windows

 (dash) or _ (underscore)Show/Hide-Window(s) toggles

The ‘‘ key turns the ´current´ window’s task display On and Off. When On, that task area will show a minimum of the columns header you’ve established with the ‘f‘ interactive command. It will also reflect any other task area options/toggles you’ve applied yielding zero or more tasks.

The ‘_‘ key does the same for all task displays. In other words, it switches between the currently visible task display(s) and any task display(s) you had toggled Off. If all 4 task displays are currently visible, this interactive command will leave the summary area as the only display element.

= or +Equalize-(re-balance)-Window(s)

The ‘=‘ key forces the ´current´ window’s task display to be visible. It also reverses any ‘i‘ (idle tasks), ‘n‘ (max tasks) and ‘u‘/’U‘ (user filter) commands that might be active. Also, if the window had been scrolled, it will be reset with this command.

The ‘+‘ key does the same for all windows. The four task displays will reappear, evenly balanced. They will also have retained any customizations you had previously applied, except for the ‘i‘ (idle tasks), ‘n‘ (max tasks), ‘u‘/’U‘(filtro de usuário) e rolagem de comandos interativos.

UMAAlternar modo de exibição alternado

Este comando alterna entre o modo de tela cheia e o modo de exibição alternativo.

Na primeira vez que você emitir esse comando, todas as quatro telas de tarefas serão mostradas. Depois disso, quando você alternar os modos, verá apenas as telas de tarefas que você escolheu tornar visíveis.

a , wPróxima janela-avançar /

retroceder Este comando altera a janela atual, que por sua vez altera a janela para a qual os comandos são direcionados. Essas teclas agem de forma circular, para que você possa acessar qualquer janela atual desejada usando qualquer uma das teclas.

Supondo que o nome da janela esteja visível (você não ativou ‘ l ‘ Off), sempre que o nome da janela atual perder sua ênfase / cor, é um lembrete de que a tarefa está desativada e muitos comandos serão restritos.

gEscolha outra janela / grupo de campos

Você será solicitado a inserir um número entre 1 e 4 designando o grupo de campos que deve ser exibido na janela ‘atual’.

No modo de tela cheia, este comando é necessário para alterar a janela ‘atual’. No modo de exibição alternativa, é uma alternativa menos conveniente aos comandos ‘ a ‘ e ‘ w ‘.

GAlterar janela / Nome do grupo de campos

Você será solicitado a aplicar um novo nome à janela atual. Não é necessário que o nome da janela esteja visível (a opção ‘ l ‘ deve estar Ativada).

* Os comandos interativos mostrados com um asterisco (´ * ´) são utilizados além do modo de exibição alternativa.

´ = ‘,’ A ‘,’ g ‘estão sempre disponíveis.’

´ a ‘,’ w ‘agem da mesma forma com o mapeamento de cores e o gerenciamento de campos.

Rolando uma janela

Normalmente, uma janela de tarefas é uma visão parcial do total de tarefas / threads de um sistema que mostra apenas alguns dos campos / colunas disponíveis. Com essas teclas de rolagem, você pode mover essa visualização na vertical ou na horizontal para revelar qualquer tarefa ou coluna desejada.

Up , PgUpTarefas de rolagem

Mova a visualização para a primeira linha da tarefa, até que a primeira tarefa seja exibida na parte superior da janela atual. A tecla de seta para cima move uma única linha enquanto o PgUp rola a janela inteira.

Abaixo , PgDnTarefas de rolagem

Mova a visualização para baixo até a última linha da tarefa, até que a última tarefa seja a única tarefa exibida na parte superior da janela atual. A tecla de seta para baixo move uma única linha enquanto PgDn rola a janela inteira.

Esquerda, DireitaColunas de rolagem

Mova a visualização dos campos exibidos horizontalmente, uma coluna por vez.

Nota: Como lembrete, alguns campos / colunas não têm largura fixa, mas alocam toda a largura restante da tela quando visíveis. Ao rolar para a direita ou esquerda, esse recurso pode produzir alguns resultados inesperados inicialmente.

CasaIr para a posição inicial

Reposicione a exibição nas coordenadas não roladas.

FimIr para a posição final

Reposicione a exibição para que a coluna mais à direita reflita o último campo exibível e a linha inferior da tarefa represente a última tarefa.

Nota: Nesta posição, ainda é possível rolar para baixo e para a direita usando as teclas de seta até que uma única coluna e uma única tarefa sejam deixadas como o único elemento de exibição.

C 

Alternar Mostrar coordenadas de rolagem Alterna uma mensagem informativa que é exibida sempre que a linha de mensagem não estiver sendo usada de outra forma.

” coordenadas de rolagem: y = n / n (tarefas), x = n / n (campos) ”

As coordenadas mostradas como n / n são relativas ao canto superior esquerdo da janela “atual”.

y = n / n (tarefas)

O primeiro n representa a tarefa mais visível no topo e é controlado pelas teclas de rolagem. O segundo n é atualizado automaticamente para refletir o total de tarefas.

x = n / n (campos)

O primeiro n representa a coluna exibida mais à esquerda e é controlado pelas teclas de rolagem. O segundo n é o número total de campos exibidos e é estabelecido com o comando interativo ‘ f ‘.

Os comandos interativos acima estão sempre disponíveis no modo de tela cheia, mas nunca disponíveis no modo de exibição alternativa se a exibição da tarefa da janela atual estiver desativada.

Pesquisando em uma janela

Você pode usar esses comandos interativos para localizar uma linha de tarefa que contém um valor específico.

euLocate-a-string

Você será solicitado a localizar a string com distinção entre maiúsculas e minúsculas, começando pelas coordenadas da janela atual. Não há restrições no conteúdo da cadeia de pesquisa.

As pesquisas não se limitam aos valores de um único campo ou coluna. Todos os valores exibidos em uma linha de tarefa são permitidos em uma sequência de pesquisa. Você pode incluir espaços, números, símbolos e até obras de arte da vista da floresta.

Se você digitar <Enter> sem entrada, desabilitará efetivamente a tecla ‘&’ até que uma nova string de pesquisa seja inserida.

&Locate-next

Assuming a search string has been established, top will attempt to locate the next occurrence.

When a match is found, the current window is repositioned vertically so the task row containing that string is first. The scroll coordinates message can provide confirmation of such vertical repositioning (see the ‘C‘ interactive command). Horizontal scrolling, however, is never altered via searching.

The availability of a matching string will be influenced by the following factors.

a. Which fields are displayable from the total available

b. Scrolling a window vertically or horizontally

c. The state of the command/command-line toggle

d. The stability of the chosen sort column, for example PID is good but %CPU bad.

If a search fails, restoring the ´current´ window home (unscrolled) position, scrolling horizontally, displaying command-lines or choosing a more stable sort field could yet produce a successful ‘&’ search.

The above interactive commands are always available in full-screen mode but never available in alternate-display mode if the ´current´ window’s task display has been toggled Off.

Note: Whenever a search key is typed, top forces idle tasks On and user filtering Off to ensure that every task is encountered. See the ‘i‘ and ‘u/U’ interactive commands for additional information on how displayed tasks might be filtered.

Files

System Configuration File

The presence of this file will influence which version of the ‘help’ screen is shown to an ordinary user. More importantly, it will limit what ordinary users are allowed to do when top is running. They will not be able to issue the following commands.

kKill a task
rRenice a task
d or sChange delay/sleep interval

The system configuration file is not created by top. Rather, you create this file manually and place it in the /etc directory. Its name must be ‘toprc’ and must have no leading ‘.‘ (period). It must have only two lines.

Here is an example of the contents of /etc/toprc:

s # line 1: ‘secure’ mode switch 5.0 # line 2: ‘delay’ interval in seconds

Personal Configuration File

This file is written as ‘$HOME/.your-name-4-top‘ + ‘rc‘. Use the ‘W‘ interactive command to create it or update it. Here is the general layout:

global # line 1: the program name/alias notation global # line 2: id,altscr,irixps,delay,curwin per ea # line a: winname,fieldscur window # line b: winflags,sortindx,maxtasks window # line c: summclr,msgsclr,headclr,taskclr

If the $HOME variable is not present, top will try to write the personal configuration file to the current directory, subject to permissions.

Tips And Tricks

Many of these ‘tricks’ work best when you give top a scheduling boost. So plan on starting it with a nice value of -10, assuming you’ve got the authority.

Kernel Magic

For these tricks, top needs full-screen mode.

  • The user interface, through prompts and help, intentionally implies that the delay interval is limited to tenths of a second. However, you’re free to set any desired delay. If you want to see Linux at his scheduling best, try a delay of .09 seconds or less.For this experiment, under X Windows open an xterm and maximize it. Then do the following:1. provide a scheduling boost and tiny delay via:nice -n -10 top -d.09
    2. keep sorted column highlighting Off so as to minimize path length
    3. turn On reverse row highlighting for emphasis
    4. try various sort columns (TIME/MEM work well), and normal or reverse sorts to bring the most active processes into viewO que você verá é um Linux muito ocupado fazendo o que sempre é feito por você, mas não havia nenhum programa disponível para ilustrar isso.
  • Sob um xterm usando cores ‘branco sobre preto’, na tela de Mapeamento de cores da parte superior, defina a cor da tarefa como preto e verifique se o realce da tarefa está definido como negrito, não reverso. Em seguida, defina o intervalo de atraso para cerca de 0,3 segundos.Depois de exibir os processos mais ativos, você verá as imagens fantasmagóricas das tarefas atualmente em execução.
  • Exclua o rcfile existente ou crie um novo link simbólico. Inicie esta nova versão e digite ‘ T ‘ (uma chave secreta, consulte o tópico 4c. Comandos da área de tarefas, CLASSIFICAÇÃO) seguido de ‘ W ‘ e ‘ q ‘. Por fim, reinicie o programa com -d0 (atraso zero).Sua exibição será atualizada três vezes mais que a anterior, uma vantagem de velocidade de 300%. Quando o topo subir a escada TIME, seja o mais paciente possível enquanto especula se o topo chegará ou não ao topo.

Saltando Windows

Para esses truques, o topo precisa do modo de exibição alternativa.

  • Com 3 ou 4 exibições de tarefas visíveis, escolha qualquer janela que não seja a última e desative os processos inativos usando o comando ‘ i ‘ para alternar. Dependendo de onde você aplicou ‘ i ‘, às vezes várias exibições de tarefas estão saltando e às vezes é como um acordeão, pois top tenta ao máximo alocar espaço.
  • Defina as linhas de resumo de cada janela de maneira diferente: uma sem memória (‘ m ‘); outro sem estados (‘ t ‘); talvez um com nada, apenas a linha da mensagem. Em seguida, mantenha pressionado ‘ a ‘ ou ‘ w ‘ e observe uma variação nas janelas saltitantes – janelas saltadoras.
  • Exiba todas as 4 janelas e, para cada uma delas, defina os processos inativos como Desligado usando o comando ‘ i ‘ para alternar. Você acabou de entrar na zona “salto extremo”.

A janela grande do pássaro

Esse truque também requer o modo de exibição alternativa.

  • Exiba todas as 4 janelas e verifique se 1: Def é a janela ‘atual’. Em seguida, continue aumentando o tamanho da janela com o comando interativo ‘ n ‘ até que todas as outras tarefas sejam “empurradas para fora do ninho”. Quando todos estiverem deslocados, alterne entre todas as janelas visíveis / invisíveis usando o comando ‘ _ ‘ alternar. É uma experiência verdadeiramente alucinante.

livre – Exibe a quantidade de memória livre e usada.
ps – Relate o status de um processo ou processos.
pstree – exibe processos em um formato de árvore.
tempo de atividade – Exibe informações sobre há quanto tempo o sistema está em execução.

22 de novembro de 2019

Sobre nós

A Linux Force Brasil é uma empresa que ama a arte de ensinar. Nossa missão é criar talentos para a área de tecnologia e atender com excelência nossos clientes.

CNPJ: 13.299.207/0001-50
SAC:         0800 721 7901

[email protected]

Comercial  Comercial: (11) 3796-5900

Suporte:    (11) 3796-5900
[email protected]

Copyright © Linux Force Security  - Desde 2011.