сопоставление linux /dev/fb0 с DDR для отображения

La siguiente secuencia de comandos es más larga que la suya, pero toda la longitud adicional se debe a que agregué una función usagepara imprimir un mensaje de ayuda de uso (que también sirve para imprimir un mensaje de error cuando se detecta una condición de error )y agregó muchos comentarios para explicar qué hace el código y por qué.

El código que analiza las opciones y hace el trabajo es mucho más corto y simple, y más fácil de expandir (p. actualmente toma una opción -u usernamepero no hace nada con ella porque no mencionaste cómo debería usarse ). Se elimina todo el manejo especial de casos -, las "decisiones" sobre qué hacer y cómo hacerlo se toman en la declaración del caso y en algunas pruebas si/entonces inmediatamente posteriores.

También agregué una opción -dpara que pueda especificar un directorio de salida... pero eso es redundante como cualquier cosa excepto un ejemplo de cómo agregar otra opción, porque también agregué un código que verifica si el El archivo de salida contiene un carácter /, y solo antepone$outdir(renombrado desde su $DIR-. Es un buen hábito usar nombres de variables en minúsculas en su script, reservando mayúsculas para utilidades estándar )si no es así. es decir, puede usar -f /path/to/fileo -d /path/to -f file.

Por cierto, en lugar de crear un alias con la ruta completa a este script, recomiendo ponerlo en /usr/local/bino crear un directorio bin/sub -en su directorio de inicio y agregar ~/bina su $ SENDERO. Luego, puede escribir y guardar tantos scripts personalizados como desee allí.

#!/bin/bash

usage() {
  # this function prints a usage summary, optionally printing an error message
  local ec=0

  if [ $# -ge 2 ] ; then
    # if printing an error message, the first arg is the exit code, and
    # all remaining args are the message.
    ec="$1" ; shift
    printf "%s\n\n" "$*" >&2
  fi

  cat < | -d  ] <[-l] length>

Generates a random password of specified length, containing only
alpha-numeric characters.

Required arguments:

  -l      Length of password.  Just the length without '-l' also works.

Options:

  -p              Allow some punctuation characters in password.
  -s        Save output to filename.
  -d         Output directory for the save file
  -u        Username.  At present this does nothing.

  -h              This help message.
EOF

  exit $ec
}

# Initialise variables
length=''
file=''
username=''
pattern='A-Za-z0-9'
outdir=$(dirname "$0")

# -s, -l, -u and -d require an arg. -h and -p don't. The leading ':' in
# the getopts string enables 'silent' error mode (i.e. we handle
# any errors ourselves)
while getopts ':hps:l:u:d:' opt; do
  case "$opt" in 
    p) pattern='A-Za-z0-9.-@' ;;
    s) file="$OPTARG" ;;
    l) length="$OPTARG" ;;
    u) username="$OPTARG" ;;
    d) outdir="$OPTARG" ;;

    h) usage ;;
    :) usage 1 "-$OPTARG requires an argument" ;;
    ?) usage 1 "Unknown option '$opt'" ;;
  esac
done

shift $((OPTIND -1))

# Length can be specified as either `-l nnn` or just `nnn` on the cmd line
# this code exits with an error message if no length is specified.
#
# It would probably be better to give length a default value instead.
# Just change `length=''` under the Initialise variables comment above
# to whatever you want as the default, and then delete the '[ -z "$1" ]'
# line below. Remember to update the usage message - documentation should
# always match what the code does.
if [ -z "$length" ] ; then
  [ -z "$1" ] && usage 1 "Length option is required"
  length="$1"
  shift
fi

# if there are any remaining args on the line, we don't know what to do
# with them, so exit with an error message.
[ -n "$*" ] && usage 1 "Unknown arguments: '$*'"

password=$(cat /dev/urandom | tr -dc "$pattern" | head -c "$length")

# I don't know why you want an extra newline in the output, but do it anyway.
printf "$password\n\n"

if [ -n "$file" ] ; then
   # if $file doesn't have a /, pre-pend "$outdir"
   [[ $file =~ '/' ]] || file="$outdir/$file"
   printf "$password\n\n" > "$file" 
fi

Por cierto, ya existen numerosos programas generadores de contraseñas -. p.ej. pwgen y makepasswd.

Solía ​​​​usar pwgenpara generar contraseñas de más de 16 dígitos hasta que escribí mi propio generador de frases de contraseña que selecciona aleatoriamente una cantidad de palabras de /usr/share/dict/wordsy las une con -generado aleatoriamente 1 -3 dígitos números y/o puntuación. /usr/share/dict/wordses todo -en minúsculas, por lo que mi secuencia de comandos pone aleatoriamente en mayúscula algunas de las letras. Esto genera contraseñas muy largas pero fáciles de recordar. Los dígitos aleatorios, la puntuación y las mayúsculas aumentan el espacio de búsqueda para el descifrado de fuerza bruta -y ayudan a garantizar que la seguridad de la contraseña no se vea comprometida por la previsibilidad del diccionario de palabras.

por ej.

$ random-password.sh 
31 surVeying % deRAngement 6 ratiocinations 51 sunDowns
$ printf '%s' '31 surVeying % deRAngement 6 ratiocinations 51 sunDowns' | wc -c
55

La longitud de la contraseña es mucho más importante que la complejidad -cualquier contraseña de menos de 10 caracteres se puede descifrar en muy poco tiempo con -hardware moderno (un segundo o menos durante

El problema es que cuanto más larga es una contraseña, más simple debe ser para que un humano pueda recordarla. Descubrí que solo necesito recordar el inicio de la contraseña y, al escribirla varias veces, asocio automáticamente (y, por lo tanto, recuerdo )los siguientes dígitos y palabras en la frase sin sentido.

1
11.09.2018, 10:40
1 ответ

Драйвер представляет собой модуль ядра Linux.

Загрузите исходный код ядра linux, посмотрите код существующих драйверов фреймбуфера вdrivers/video/fbdev(github здесь)и документацию вDocumentation/fb(github). Google для учебников, как писать модули ядра, сначала потренируйтесь с простым модулем.

Простого сопоставления памяти будет недостаточно, вам придется реализовать несколько ioctlс.

Написание драйверов ядра — непростая задача. Если вам приходится задавать подобные вопросы (, а вы задавали их много за последние несколько дней ), вы, вероятно, не сможете это сделать.

X — это сервер для протокола X. Он может использовать оборудование через модули ядра DRM, а также может использовать оборудование через драйверы кадрового буфера (с fbdevX-драйвером ). Подробности об этом легко найти в сети, погуглить. /dev/fb0— это устройство кадрового буфера, поэтому вам не нужно беспокоиться о X или DRM.

3
28.04.2021, 23:42

Теги

Похожие вопросы