Linux & Python for Raspberry Pi: Getting started with Linux & Python
معرفی کتاب «Linux & Python for Raspberry Pi: Getting started with Linux & Python» نوشتهٔ William Edison، منتشرشده توسط نشر William Edison در سال 2019. این کتاب در فرمت pdf، زبان انگلیسی ارائه شده است. «Linux & Python for Raspberry Pi: Getting started with Linux & Python» در دستهٔ بدون دستهبندی قرار دارد.
Learn to create inventive programs on your powerful Raspberry Pi and Linux & Python―with no programming experience required. This practical book has been revised to fully cover the new Raspberry Pi 3, including upgrades to the raspbian operating system. Discover how to configure hardware and software, write Linux & Python scripts, create user-friendly GUIs, and control external electronics. DIY projects include a digital output – LED RBG, Relay. Digital input –swich up/down or sensor LDR. Analog output servo motor controller. Build Internet of Thing (IoT) applications. Open sourch computer vision (OpenCV) with camera sense motion, image face/eye detecting. * Set up your Raspberry Pi and explore its features * Linux basic with command syntax, Linux file & directory command, standard I/O, file permission, file system and link * Linux shell scripting, VI Editor, Shell programming, process and system innitialization, user, utilities & APT * Python basic with syntax, data structure, function module, class, file I/O, thread, networking * Control dive with python web programing, HTTP, flask, web socket * Using python to drive hard ware GPIO, digital output, digital input, analog output – PWM, analog input – RC Circuit, high level sensor modules * Building raspberry-pi communication, serial, UART, I2C, SPI, bluetooth, BLE-Beacon * Raspberry-Pi Multimedia, buzzer, audio, camera, CCTV, computer vison with open CV face /eye detecting * Add powerful Web IoT with GPIO and camera web streaming * Set up your Arduino and developing environment, digital I/O, analog I/O control circuit 1. Installation 1.1 Introduction 1.2 Os(Rasbian) Installtion 1.3 Development Environment 2. Linux Basic 2.1 Introduction to Unix & Linux 2.2 Linux Command Syntax 3. Linux File System 3.1 File & Directory Command 3.2 Standard I/O 3.3 File Permission 3.4 File System and Link 4. Shell Scripting 4.1 VI Editor 4.2 Shell programming 5. Process & System 5.1 Process 5.2 System Initialization 5.3 User 5.4 Utilities & APT 6. Python Basic 6.1 Introduction 6.2 Syntax 6.3 Data Structure 6.4 Function 6.5 Module 6.6 Class 6.7 Exception 6.8 File I/O 6.9 Thread 6.10 Networking 7. Python Web Programming 7.1 Introduction 7.2 HTTP 7.3 Flask 7.4 WebSocket Chapter2: Raspberry-Pi for Prototyping 1. Raspberry-Pi & GPIO 1.1. GPIO 1.2. Digital Output 1.3. Digital Input 1.4. Analog Output – PWM 1.5. Analog Input – RC Circuit 1.6. High Level Sensor Modules 2. Raspberry-Pi Communication 2.1 Serial Communication 2.1 UART 2.1 I 2 C 2.1 SPI 2.1 Bluetooth 2.1 BLE - Beacon 3. Raspberry-Pi Multimedia 3.1 Buzzer 3.2 Audio 3.3 Camera 3.4 CCTV 3.5 OpenCV Computer Vision 8. Raspberry-Pi Web IoT 8.1 Introduction 8.2 Web with GPIO 8.3 Camera Web Streaming 9. Appendix 9.1 Arduino Raspberry-Pi https://en.wikipedia.org/wiki/Raspberry_Pi Eben Upton, UK Raspberry Pi Foundation Founder For teaching computer science in developing countries 2011, Alpha board 2012, First sales Broadcom BCM2835 SoC Designed as a PC, Not a development board Raspberry Pi Boards Series https://www.raspberrypi.org/products/ Raspberry Pi Boards Series Raspberry Pi 3 ARMv8 CPU 1.2GHz 64bit quad-core 802.11n Wireless LAN Bluetooth 4.1 Bluetooth Low Energy(BLE) 1GB RAM 4 USB ports 40 GPIO Pins Full HDMI port Ethernet port 3.5mm audio Camera interface(CSI) Display interface(DSI) Micro SD card slot VideoCore IV 3D graphics core Raspberry Pi 3 OS image file download https://www.raspberrypi.org/downloads/raspbian/ 201x-xx-xx-raspbian-jessie.zip Raspbian Jessie with PIXEL : Full Image with PIXEL Desktop Jessi Lite : Minimal Image Burn Image to SD Card ETCHER https://etcher.io/ Windows, MacOSX, Linux Win32Disk Imager https://sourceforge.net/projects/win32diskimager/ Windows Only setup As a PC Connect Monitor, Keyboard, Mouse and Internet Network setup SSH Connection As a develop board Serial Consol TTY USB-Serial Convertor USB(PC) to UART(R-Pi) Network setup SSH Connection Direct Ethernet cable(Internet Sharing) Ethernet(PC) – Ethernet(R-Pi) Network setup SSH Connection As a PC Easiest way to setup but inconvenient Connecting Monitor using HDMI Cable Mouse/Keyboard using USB Ethernet Cable Insert SD Card Power In As a PC open editor as sudo Run sudo leafpad As a PC static IP setup File > Open /etc/dhcpcd.conf Serial Console TTY Enable Eject SD card reader and Connect to PC again Check ‘boot’ drive and 2 files in it cmdline.txt config.txt cmdline.txt (Just checking) config.txt add “enable_uart=1” at the end of the file no spaces in the line Eject SD card from PC, Insert into R-Pi SD slot No Powering to Raspberry Pi yet. Static IP setup sudo vi /etc/dhcpcd.conf (Must Back-up) sudo reboot ifconfig eth0 Check IP address Network Check ip ifconfig ip address Router route ip route DNS cat /etc/resolv.conf Wifi setup sudo iwlist wlan0 scan sudo vi /etc/wpa_supplicant/wpa_supplicant.conf sudo ifdown wlan0 sudo ifup wlan0 ifconfig wlan0 Check IP address SSH Login PuTTy Connection Type : SSH Host Name : Raspberry Pi IP Adress Port : 22 Save RSA Key Login ID : pi Passwrd : raspberry Software Configuration sudo raspi-config 4 Internationalisation options Time Zone > Asia > Seoul Change Locale en_US.UTF-8 ko_KR.EUC-KR ko_KR.UTF-8 Default : en_US.UTF-8 Change Keyboard layout Generic 105-Key Korean-104Key Compatible Module Update sudo apt-get update sudo apt-get upgrade Install Korean Font sudo apt install fonts-unfonts-core Install Korean Keyboard Input sudo apt install ibus sudo apt install ibus-hangul LCD Monitor setup http://elinux.org/index.php?title=RPiconfig /boot/config.txt BIOS in PC max_usb_current Change Usb output limits 600mA j1200mA hdmi_group 1 : CEA, 2: DMT hdmi_mode=87 Custom mode hdmi_cvt width, height, framerate, aspect, margins, interlace, rb Remote Desktop - VNC Raspberry-Pi Configuration GUI Interfaces Enable VNC Service Raspberry-Pi Configuration CLI sudo raspi-config Interfaces VNC Remote Desktop - VNC Raspberry-Pi Server Installation sudo apt-get install x11vnc Execute Server x11vnc Adjust Resolution http://elinux.org/Rpiconfig /boot/config.txt Remote Desktop - VNC PC http://www.realvnc.com/download/ Install VNC Viewer Remote Desktop - xrdp Raspberry-Pi Server Installation sudo apt-get remove vnc4server sudo apt-get remove tightvncserver sudo apt-get install tightvncserver sudo apt-get install xrdp File for server setting /etc/xrdp/xrdp.ini PC(Windows Only) Start > mstsc (Remote Desktop) sesman-XVnc pi / raspberry Python https://www.python.org/downloads/release/python-2711/ Version 2.7.x, Not 3.5.x Python Installation on PC Default Path Enable "Add python.exe to path" Option Python Hello World REPL(Read-Eval-Print-Loop) open Windows command console execute 'python' command python shell prompt opened execute 'print "Hello world" command 'exit()' Source Code make a file named 'hello_world.py' execute command python hello_world.py WinSCP SFTP : FTP based on SSH Transfer/ Receive File https://winscp.net/eng/download.php WinSCP Installation Default Options WinSCP Connect to RaspberryPi WinSCP Left Pannel : PC Local File System Right Pannel : Remote, RaspberryPi File System File upload : File > Upload (F5) to /home/pi Python on RaspberryPi Open PuTTY Check the file "hello_world.py" uploaded ls hello_world.py Execute python hello_world.py GCC Cross Compiler for RaspberryPi http://gnutoolchains.com/raspberry/ Appropriate version for Raspbian Image installed GCC Cross Compiler for RaspberryPi Install on PC Default Options GCC Cross Compiler for RaspberryPi Check Installation C:\SysGCC\Raspberry\bin\arm-linux-gnueabihf-gcc --version Source Code "hello_world.c" make file named hello_world.c GCC Cross Compiler for RaspberryPi Compile arm-linux-gnueabihf-gcc -o hello_world hello_world.c Check the output file named "hello_world" Upload to RaspberryPi using WinSCP /home/pi/hello_world Check and change permission the file on RaspberryPi ~$ file hello_world ~$ chmod 777 hello_world execution the file ~$ ./hello_world NodeJs Download for PC(Windows) https://nodejs.org LTS Version NodeJs Installation on PC Default Options NodeJs Download for RaspberryPi Too old version(v0.10.x) is installed by default Determine download version with CPU archtecture $ uname –m or $ lscpu or $ cat /proc/cpuinfo RaspberryPi CPU is ARMv8, but Rasbian OS is based on 32bit NodeJs Download wget https://nodejs.org/dist/v6.9.4/node-v6.9.4-linux-armv7l.tar.xz Extract tar –xf node-v6.9.4-linux-armv7l.tar.xz move to /opt sudo mv node-v6.9.4-linux-armv7l /opt/nodejs create link apt-get remove nodejs sudo ln –s /opt/nodejs/bin/node /usr/bin/node sudo ln –s /opt/nodejs/bin/npm /usr/bin/npm NodeJs check nodejs version $ node –version Source Code make the file named 'hello_world.js' on PC Run on PC node hello_world.js Upload and Run on Raspberry upload the file using WinSCP node hello_world.js JDK(Java Development Kit) Installation Needed for Eclipse http://java.sun.com http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html Eclipse Installation http://www.eclipse.org/downloads/ Eclipse IDE for JavaEE Developer PyDev Installation Eclipse > Help > Eclipse Marketplace Search "Python" PyDev Configuration Eclipse Preferences Pydev > Interpreters > Python Interpreter Quick Auto-Config Python Project Create a Python new project New > Project Create a Python Source Code File New > PyDev Module Python Project Python Code Running R Click > Run As > Python Run Eclipse CDT(C/C++ Development Tooling) Installation Eclipse Help > Install New Software Click Add Button Name : CDT Location : http://download.eclipse.org/tools/cdt/releases/9.2 Eclipse CDT(C/C++ Development Tooling) Installation Eclipse Help > Install New Software Add Button Click Name : CDT Location : http://download.eclipse.org/tools/cdt/releases/9.2 check all items uncheck Arduino C++ Tools C Project R Click > New Project C Project Fill in the Project Name Project Type Hello World ANSI C Project Toolchanis Cross GCC C Project Basic Settings Fill in the blanks appropriately C Project Select Configurations Leave it as defaults Checked Debug, Release C Project fill in the blanks correctely cross compiler prefix arm-linux-gnueabihf- cross compiler path C:\SysGCC\Raspberry\bin Path of the Cross Compiler C Project C Source code Build Menu > Project > Build All Check the result Console message output file under Debug C Project Running Upload using WinSCP Execute the file on the RaspberryPi using PuTTY Eclipse NodeJs Configuration Nodejs Plugin Installed by default on Eclipse Neon Check the Configuration You can customize NodeJs Project Create a Nodejs Project R Click > New Project > Javascript Project NodeJs Project Fill in the project name Leave all other items as default Click Finish NodeJs Project Create Source Code File R Click > New > File Fill in the File Name with .js extention Click Finish button Edit File Running R Click > Run As > Node.js Application Check the result on the Console RemoteSystem Setup You can control the Remote RaspberryPi with Eclipse Open Perspective Eclipse > Window > Perspective > Open Perspective > Other Remote System Explorer RemoteSystem Setup Register a new Connection Remote System > R Click Login Apply Python Project to Remote Export project produced in PyDev Perspective Remote Systems > Remote File System Apply Python Project to Remote Select a directory on RaspberryPi Apply Python Project to Remote Select Destination Check "Review/Sysnchronize" Option Apply Python Project to Remote Put the file to apply using Synchronize view Apply Python Project to Remote Executing remotely using PuTTY. Apply C Project to Remote R Click on the Project Run As > Run Configurations Select "C/C++ Remote Application" create new run configuration new connection connection type SSH Apply C Project to Remote New Connection Fill in the blanks Remote path Select properly path on the remote Raspberry Pi Apply C Project to Remote Commands to execute before application chmod 744 path/to/output_file_name Check the result in the Console view Apply NodeJs Project to Remote NodeJs Project Export Remote Systems > Remote File System Select a directory on RaspberryPi Check "Review/Synchronize" option Apply NodeJs Project to Remote Put the file to apply using Synchronize view Executing remotely using PuTTY. Unix Multics for GE646 by AT&T, GE, MIT in 1964 Multi User, Multi Processing, Multi Process Pulled down for many problems in 1969 Unix AT&T Lab 1971' Re-do in Assembly by Ken Thompson(US, 1943 ~ ) 1973' Re-written in C language by Dennis Ritchie US, 1941 ~ 2011 Developed C language to Write Unix UC Berkley Buy Source Code from AT&T Added TCP/IP Stack BSD version System V from AT&T Solaris, HP-UX, AIX BSD from UC Berkley SunOS, FreeBSD Minix Minimal Unix-like OS, 1987 Andrew Stuart(Nederland, 1944~) For Education only Linux 1991' University of Helsinki, Linus Torvalds(Finland, 1969~) Created Unix like OS on Minix Free Software, GNU GPL Distributions Red Hat Famous in Enterprise Server Package Manager : RPM Fedora, CentOS, 붉은별 Debian Famous in Desktop Package Manager : APT Ubuntu, Rasbian, Mint Slack ware OpenSUSE, Slax Unix like System Minix Linux Mac OSX POSIX(Portable Operating System Interface) suggested by Richard Stallman(1953 ~ ) in 1985 Standards for Unix Interface Certified AIX HP-UX IRIX macOS, Darwin Solaris FreeBSD NetBSD Linux VxWorks Unix/Linux System Structure Kernel File System Shell Kernel Core Component Device Management Memory, Process Management File System Management CPU Control File System Hierarchical Directory and File, /(root) Managing Files in Disks Mapping Devices, Processes to Files Linux FS Ext3, Ext4 Shell Interfacing between Human and Kernel Shells Bourne Shell Unix Orinate C Shell Similar C language Korn Shell Unix Standard Improved Bourne & C Bash Shell Most Linux Shells Bourne Again Z Shell Mordern Style Command Line Interface Command Shell Built-in Command Execution File in PATH Options Optional dash(-) character Additional Requirements Modifiers for Command Arguments Optional or Mandatory Object of Command Target to Execute Command Line Interface Command Only No options Default Options No arguments Objects or Targets omitted Examples uname date cal ls Command Line Interface Command + Options Additional Requirements Common Options -a : all Command Line Interface Command + Arguments Target Specific No omitted Command Line Interface Command + Options + Arguments Command chaining Executing Multi Commands Simultaneously ; - Semi Colon(;) command-1; command 2; command-n sequential Separated N command No effect error && - Ampersand X 2 No Single & (Background) Depends on Error Stop If Error Occurs Control Characters Process Ctrl + c : Interrupt(terminate) current process, SIGINT Ctrl + d : EOF(End of File) or EOT(End of Transmission) Character Ctrl + z : Suspend current foreground process, SIGSTP Cursor Ctrl + a : move cursor to start of line Ctrl + e : move cursor to end of line Screen Ctrl + u : Clear current line Ctrl + w : Clear current word Ctrl + l : Clear screen Ctrl + s : Stop output to the screen Ctrl + q : Resume output to the screen stopping with Ctrl + s Types of Command Shell Built-in Internal Command Shell Command Executable Program File External Command All Files has X mode in disk Specified the location in $PATH env /bin : basic command for normal users /sbin : basic command for administrators /usr/bin, /usr/sbin : command for specific class user ex : office user, developer, gamer /usr/local/bin, /usr/local/sbin : user compiled, installed program Types of Command Shell Built-in List up help Detail Information help Distinguish type Executable Program File List up echo $PATH Detail Information --help man help Location which Manual page From Unix Manual Paper Book online : http://man7.org/linux/man-pages/index.html Manual page man Navigate key enter : next line space : next page b : prev page /pattern : search pattern n : next pattern q : exit SEE ALSO Relative Command Section Number Command(n) Manual page Inquiring in section man –s man Keyword man –k pwd present working directory ls list up files and directories ls options pathname -l : long, detail -a : all, no hidden file -d : directory -R : recursive -F : file type / : directory * : executable (none) : text @ : link ls file ls /dir ls -l Tree list directory like tree-format -d : directory only -L : depth level -P : pattern only -I : ignore patten File determine file type -i : MIME type -L : symlink Stat display file or file system status Directory Command mkdir make directory -p : make parent cd change directory Path Absolute vs Relative . : current dir .. : parent dir ~ : home dir / : root dir - : previous Making a File touch no content in the file zero size echo 'content' > echo 'hello world' > hello.txt echo & redirection Editor nano vi Nano Editor Linux Basic Test Editor nano [FILENAME] Ctrl + X : eXit Ctrl + O : Save Ctrl + K : Cut, Copy Ctrl + U : Paste Ctrl + ^ : Block Ctrl + W : Search Ctrl + G : Help cp (Copy) Copy File or directory cp option source target File Copy new file name cp fileA fileAA new file name to other dir cp fileA dirA/fileAA no file name to other dir cp fileA dirB -i : Interactive prevent overwriting cp (Copy) Directory Copy -r : recursive To new directory cp –r dirA dirZ create new directory To existing directory cp –r dirA dirB copy to child directory mv (Move) Move File or Directory To Move File File name only mv fileA fileX The same with rename New path mv fileB dirB/fileX mv (Move) To Directory To new directory mv dirA dirX create new directory To existing directory mv dirB dirC move to child directory rmdir (Remove Empty Directory) rmdir [option] DIRECTORY... -p : parent Remove ancestors only empty directory if not empty fail use rm rm (Remove File or Directory) rm [options] file_path -r : recursive Not Empty -f : force ignore nonexistent -d : empty directory Display File content cat [OPTION] [FILE] concatenate file to output If no file, standard input more FILE paging one screen scroll enter : next line space : next page b : prev page / : search n : next pattern q : quit head [OPTION] [FILE] output the first part -n : first NUM lines tail [OPTION] [FILE] output the last part -n : last NUM lines -f : following wc (Word Count) wc [OPTION] FILE no option : lines, words, bytes -l : line counts -w : word counts -c : byte counts -m : character counts useful with pipe(|) grep grep [OPTION] PATTERN [FILE..] print lines matching a pattern OPTION -i : Ignore case -l : print file name -n : line number -v : invert match -c : count -w : word searching -E : extended regexp -F : fixed string -r : recursive egrep grep -E fgrep grep –F rgrep grep -r find search files find path expression action expression -name filename 'filename*' : * with quotation mark -type filetype : f, d, c, b ... -size [+|-]n[c,k,M,G] -atime, -amin, -mtime, -mmin, -ctime, -cmin [+|-]n -user owner_id -perm [-|/] mode - : match all bit / : match any bit -maxpeth n find expression find expression find –perm find search files find path expression action action -print(default) : path and name -ls : print detail -delete : delete files -exec command [{}] \; -exec command {} + execute command {} : Result of find \; : execute separately + : execute at once -ok command [{}] \; : execute command interactively find action find –exec Standard I/O Redirection Input from file instead of stdin file_name : overwrite >> file_name : append output to file instead of stderr 2> file_name : overwrite 2>> file_name : append Redirection /dev/null Null Device Special File to discard useless data command 2> /dev/null discarding useless error messages > file_name 2>&1 Redirecting stdout, stderr to same file Pipe ( | ) Connect stdout of process(A) to stdin of another process(B) A | B tee Read from stdin, write to stdout and file Good for output both stdout(terminal) and file Using Redirection and Pipe Together -a : append Linux File Mode Determine can read, write, execute File type - : Normal file d : Directory l : Symbolic link s : socket p : Named Pipe c : Character device b : Block device User Owner Owner ID Group Member of the group Other Not a owner, Not a member File Permission Determine Permission id [USER] print user and group Change Permission chmod mode filename symbolic mode Target u : owner g : group o : other a : all (default, except umask bit) Operator + : add - : remove = : assign Permission r : read w : write x : execute Change Permission Symbolic mode Change Permission chmod mode filename Octal mode 3 digit in octal Change Permission Octal Mode Change Owner chown id FILENAME chown id : group FILENAME chown :group FILENAME Change Group chgrp gid FILENAME Umask newly created file's permission umask : print umask umask value : set umask Umask Calculation Default – Umask_value 2's Complement of umask AND operation Default Permission Directory : 777 File : 666 Example, umask=0022 Umask File System Control how data(File) is stored and retrieved Windows : FAT, NTFS, exFAT Unix : UFS Linux : Ext2/3/4, XFS,JFS MacOS : HFS Flash : UBIFS, JFFS2, YAFFS Linux File System Boot Block (Boot Sector) At the beginning of Storage Special data to start a system Super Block File system metadata (Type, Size, Status) Information of I-Node, Data block I-Node Block Represents a File Stores data of permission, owner, size, pointer of Data Block Data Block Contain file data and directory can be multiple per file I-Node & Data Block ls –il -i : inode Directory Directory is a file Stores file list Pair of I-Node number and file name Link Count Every Directory has 2 items . (Current) .. (Parent) Sub Directory Count Link Connection between a file and data Hard Link Low-level link Make another File Name But not make I-Node, has the same I-Node number No difference between the original and the link Increment Link Count Cannot make a hard-link to directory Soft(Symbolic) Link Similar to Windows shortcut icon Make a new file pointing to the original file File Type : l, @ Permission : 777 Link Update and Read Always the same effect Original, Hard-link, Soft-link Remove Link Remove origin No effect on hard-link Make Dangling soft-link Restorable, Creating a file with the same name as origin Remove hard-link No effect on origin, soft-link Remove soft-link No effect on origin, hard-link Finding Link Hard link find . -samefile find . -inum Symbolic link find . -lname vi [File Name ] Mode command mode edit mode last line mode: Input command at the last line Vi Edit Mode i : Input in front of curser a : Input after the curser o : Input after adding a line at the end of curser O : Input after adding a line before curser A : Input at the end of curser line I : Input in front of curser line r : Overwrite one unit at the curser position R : Overwrite exiting character from curser position x : Delete a unit dd : Delete a line u : Redo Vi Moving Curser h : Move left j : Move down k : Move up l : Move right ^ , 0: To the beginning of the line $ : To the end of the line G : To the end of the document 1G : To the beginning of the document Number G : Move to number line Ctrl + D : A half page down Ctrl + F : A half page up Ctrl + B : One page up Ctrl + U : One page down Vi Copy/ Paste yy : Copy the line with curser Number yy : Copy lines as numbered x : Cut one unit where the curser is located p : Paste Number p : Paste lines as numbered Block Mode v : Blurred Mode y : Block Copy p : Block Paste d : Block Delete > : Block Tap A –lt B : check if A is less than B, = A –le B: check if A is less than or equals to B, dash , minimal shell of bash for executing shell execute command in the new shell process my.sh chmod +x she bang #! /bin/sh #! /bin/env sh execute command in the current shell process source my.sh source : execute command in the current shell process . my.sh . is alias for source Shell Initialization When the shell is invoked, startup files system wide startup /etc/profiles set PATH, PS2 invoke /etc/profile.d/*.sh /etc/profile.d/*.sh custom changes user-specific startup ~/.bashrc ~/.bash_aliases invoked from ~/.bashrc Shell Initialization alias [-p] list up defined alias alias NAME=VALUE define alias NAME for VALUE ~/.bash_aliases invoked from ~/.bashrc 23 Handy bash shell aliases https://www.linuxtrainingacademy.com/23-handy-bash-shell-aliases-for-unix-linux-and-mac-os-x/ Process An Instance of Program running init (systemd) process /sbin/init j /lib/systemd/systemd First process after booting Ancestor of all process PID(Process Identifier) is1 ps –p 1 Parent Process process that created child Child Process process that is created by parent Deamon Process not require controlling terminal Orhpan Process parent dies or get killed before the child init process adopts Zombie Process child dies but parent does not fetch termination status Searching Process ps –ef | grep command pgrep –l command SIGNAL Limited form of Inter Process Communication Signals kill -l SIGNAL Major Signals sending signal kill –signal target Background Process command & run in background ctrl + z go stopped in background jobs list up background run in background fg [job_id] run in foreground nohup run command ignoring hangup signals nohup COMMAND & Init and Systemd First Process started during booting continues running until the system is shut down SysV style Traditional init system from Unix 7 Run-levels /etc/inittab /etc/init.d/* /etc/rc[0-6, S].d/* systemd Replacements for init Since Debian Jessie v8, 2015 RedHat v7.0, 2014 /lib/systemd/systemd /lib/systemd/system/*.service Run Level mode of operation 7 run-levels in Linux SystemV init Run Level Systemd target Mapping runlevels and systemd target Determine current run level runlevel who –r Change run level sudo init [0-6] shutdown -P : power off -h : power off -H : halt, lowest state leaves it power on -r : reboot -c : cancel shutdown -k : shudown warning to users halt -p : poweroff poweroff : power off the machine reboot : reboot the machine wall : write a message to all user Run Level Setting Run Level /lib/systemd/system/default.target change symbolic link to /lib/systemd/system/poweroff.target ( runlevel0 ) /lib/systemd/system/rescue.target ( runlevel1 ) /lib/systemd/system/multi-user.target (runlevel2, 3, 4) /lib/systemd/system/graphical.target (runlevel5) /lib/systemd/system/reboot.target (runlevel6) Startup Service Process that require autorun after booting /etc/rc.local System V Init Style Compatable Invoked by /lib/system/system/rc-local.service add command in the file /lib/system/system/myd.service Systemd Init Style Create .service file systemctl enable systemctl start systemctl stop systemctl disable Example shell, myd.sh write time to ~/date.log every seconds save as /home/pi/myd.sh chmod +x myd.sh Startup Service Easy way : rc.local open /etc/rc.local add the command that invokes myd.sh before "exit 0" su – pi –c '~/myd.sh' & Reboot and Check the process Startup Service Add Service : myd.service Create file /lib/systemd/system/myd.service Startup Service Add Service : myd.service Enable and Start Reboot and Check the Process Stop and Disable Getting User Information Determine Current or User id [ID] who am i Get all users logined who users /etc/passwd stores all user accounts information Getting User Information sudo passwd -aS display all user accounts information Getting User Information sudo chage -l display user accounts expiry information Adding User Account sudo adduser add a user or group to the system Changing Password passwd own password passwd must not be short sudo passwd someone else's password passwd can be short Creating Group sudo groupadd add a group to the system List up all Groups cat /etc/group Adding a user to an Group sudo adduser Remove a user from group sudo deluser Getting Super User authority add user to sudo group /etc/sudoers sudo adduser sudo Sudo with No Password make a file in /etc/sudoers.d no contain '~' or '.' Substitute User su [-] - , -l, --login : login shell Unset all variable and set again Change Home directory Become a Root su – root su - Remove a existing group from system sudo delgroup Remove a User from system sudo deluser Enabling Root Account NOTE : Not Recommended Root Account is locked and not set password Unlock Set New Password Enabling Root Account NOTE : Not Recommended Allow login through ssh /etc/ssh/sshd_config #PermitRootLogin prohibit-password j PermitRootLogin yes Disabling Root Account Lock Account Delete Password sudo passwd –dl root top, htop Display Processes, cpu info, memory info df Show disk space usage -k : kilo -h : human readable tar (tarballs) make archive file tar -cvf a.tar /abc /def aaa bbb make archive with zip compression tar -cvzf a.tar.gz /abc /def aaa bbb extact archive file tar –xvf a.tar extract archive with zip compression tar –xvzf a.tar.gz Disk Utilities lsblk list block devices fdisk manipulate disk partition table -l : list up dd data duplicate, convert and copy a file dd bs=n if=input_file of=output_file mount -l : list up mount [Device] [Mount_point] umount unmout file system umoun
دانلود کتاب Linux & Python for Raspberry Pi: Getting started with Linux & Python