iniciada e fechada ou finalizada

0

Eu estou olhando para monitorar processos que são iniciados ou fechados por um usuário ou sistema em um script bash. Existe alguma maneira de verificar qual processo é iniciado agora e para o processo fechado que esse processo está fechado agora?

#!/bin/bash

while true
do
OUTPUT="$(ps aux | wc -l)"
echo "First ${OUTPUT}"
sleep 5
OUTPUT1="$(ps aux | wc -l)"
#echo "Second ${OUTPUT1}"

#if [ "${OUTPUT}" == "${OUTPUT1}" ]; then
#echo "procesess same"

if [ "${OUTPUT}" -lt "${OUTPUT1}" ]; then
echo "procesess Increased"

elif [ "${OUTPUT}" -gt "${OUTPUT1}" ]; then
echo "procesess decreased"

fi
done

Estou usando este código, que é apenas mostrar que a contagem de processos é aumentada ou diminuída. Então, como expandir isso para que, se aumentados, quais processos foram adicionados e diminuídos quais processos foram encerrados?

    
por hash 30.11.2016 / 22:29

1 resposta

0

Para fazer isso, você precisará armazenar a saída de ps aux em uma variável e fazer um pós-processamento com ferramentas como awk , sed e similares.

Aqui está um exemplo de tal implementação:

#!/bin/bash
PS_OUT="$(ps aux)"
while true
do
    NEW_OUT="$(ps aux)"

    # quick explanation :
    # - NR==FNR : in the case of the 1st file
    #   -> we create the dictionary : a[line] = 1
    # - NR!=FNR : in the case of the 2nd file
    #   -> we add 2 to the value of the dictionary a[line]
    awk 'NR==FNR{a[$0]++} NR!=FNR{a[$0]=a[$0]+2}
    END{
            # for every existing key in our dictionary ...
            for (l in a)
            {
                    # if a[line] is equal to 1, it was only encountered in  the first file
                    if (a[l]==1) print "process removed : "l

                    # if a[line] is equal to 2, it was only encountered in  the second file
                    if (a[l]==2) print "process added :   "l
                    # if it was encountered in both files, it should be equal to 3
            }
    # we substitute the content of our variables so that awk considers them as input files
    }' <(echo "$PS_OUT") <(echo "$NEW_OUT")

    PS_OUT="$NEW_OUT"
    sleep 5
done
    
por Aserre 02.12.2016 / 12:59