> and >> in shell redirection?Answer: > truncates (overwrites) the target file before writing. >> appends to the file. Example:
xxxxxxxxxxecho "hello" > file.txt # overwritesecho "world" >> file.txt # appendsAnswer:
xxxxxxxxxxcommand > out.txt 2>&1 # classic formcommand &> out.txt # bash shorthand2>&1 redirects file descriptor 2 (stderr) to wherever fd 1 (stdout) currently points.
set -e do in a bash script?Answer: Causes the script to exit immediately if any command returns a non-zero exit status. Often combined with set -u (treat unset variables as errors) and set -o pipefail (fail if any command in a pipeline fails).
Answer: Single quotes (') preserve every character literally — no variable expansion or escape sequences. Double quotes (") allow variable expansion ($VAR), command substitution (`cmd` or $(cmd)), and escape sequences (\n, \\).
Answer: A subshell is a child process that inherits the parent shell's environment but changes to variables or cd do not affect the parent. Created by: (cmd) grouping, command substitution $(cmd), pipelines (each pipeline element may run in a subshell), and backgrounded jobs.
exec differ from running a command normally?Answer: exec replaces the current shell process with the given program — no new process is forked. The PID stays the same. If used inside a script, the script process is replaced and code after exec never runs (unless exec fails).
/dev/null?Answer: /dev/null is a special device file that discards all data written to it and returns EOF when read. Used to suppress output: cmd > /dev/null 2>&1.
xxxxxxxxxxfind /path -mtime -1 -type f-mtime -1 means modified less than 1×24h ago. -mtime +1 means more than 1 day ago.
xargs and give a practical example.Answer: xargs reads items from stdin (delimited by whitespace/newlines) and executes a command with those items as arguments. Useful when a command doesn't accept stdin directly.
xxxxxxxxxxfind . -name "*.log" | xargs rm -ffind . -name "*.c" | xargs -P4 gcc -c # parallel compilationtee do?Answer: Reads stdin and writes to both stdout and one or more files simultaneously. Useful for logging while still seeing output:
xxxxxxxxxxmake 2>&1 | tee build.logwhich, type, and whereis?Answer:
which — searches $PATH and prints the path of the executable.
type — bash built-in; identifies whether a name is a function, alias, built-in, or file.
whereis — searches standard binary, source, and man-page locations.
Answer: $? holds the exit status (0 = success, non-zero = failure). In pipelines, ${PIPESTATUS[@]} holds per-command statuses.
$@ vs $* in bash?Answer: Both expand to all positional parameters, but "$@" preserves individual argument boundaries (each arg quoted separately), while "$*" joins them with the first char of IFS. Use "$@" when passing arguments through.
xxxxxxxxxxcat <<EOFline oneline twoEOF<<-EOF strips leading tabs (useful for indented scripts). <<'EOF' suppresses variable expansion.
[ ] and [[ ]] in bash conditionals?Answer: [ ] is the POSIX test command — limited operators, word splitting applies. [[ ]] is a bash keyword — supports regex (=~), pattern matching, &&/|| without quoting issues, and no word splitting.
Answer: A process is a running instance of a program. It has a unique PID, its own virtual address space, file descriptors, credentials (UID/GID), and associated kernel data structures (task_struct). Processes are created via fork() and execute programs via exec().
Answer: Threads (lightweight processes) share the same virtual address space, file descriptors, and signal handlers as their parent process. Separate processes have independent address spaces. In Linux, both are implemented via clone() with different flag combinations. Threads share mm_struct; processes get a copy-on-write clone.
Answer:
Running (R) — executing on CPU or runnable (in run queue).
Sleeping (S) — interruptible sleep, waiting for event (can receive signals).
Uninterruptible sleep (D) — waiting for I/O; cannot be killed by signals (even SIGKILL).
Stopped (T) — stopped by SIGSTOP or debugger.
Zombie (Z) — finished but parent hasn't called wait(); holds PID and exit status.
Dead (X) — transient state, being cleaned up.
Answer: A zombie is a process that has exited but whose parent hasn't called wait() to collect its exit status. It consumes a PID and a minimal task_struct entry. To remove: send SIGCHLD to the parent (to trigger wait()), or kill the parent (init/systemd will reparent and reap). You cannot kill a zombie directly.
Answer: A process whose parent has exited before it. Linux reparents orphans to PID 1 (init/systemd), which periodically calls wait() to reap them.
fork() work?Answer: fork() creates a child process by copying the parent's address space (using copy-on-write). The child gets a new PID and its own file descriptor table (sharing the underlying open file descriptions). fork() returns 0 in the child and the child's PID in the parent (or -1 on failure).
Answer: After fork(), parent and child share the same physical pages, marked read-only. When either process writes to a page, the kernel makes a private copy for the writer. This avoids copying the entire address space upfront, making fork()+exec() efficient.
xxxxxxxxxxkill -SIGTERM <pid> # graceful terminationkill -9 <pid> # SIGKILL — cannot be ignoredkill -SIGHUP <pid> # hangup (often causes reload)pkill -f pattern # by name/patternkillall nginx # by nameAnswer: SIGTERM (15) is a polite termination request — the process can catch it, clean up, and exit gracefully. SIGKILL (9) is sent directly to the kernel; the process cannot catch, block, or ignore it. The kernel forcibly terminates it. Always try SIGTERM first.
Answer: SIGKILL (9) and SIGSTOP (19) cannot be caught, blocked, or ignored — they are handled directly by the kernel.
Answer: A process group is a collection of processes, typically a pipeline. The process group leader has the same PGID as its PID. A session groups process groups, created by setsid(). The session leader's SID equals its PID. Terminal signals (Ctrl+C → SIGINT) are sent to the foreground process group of the controlling terminal.
xxxxxxxxxxcommand & # start in backgroundjobs # list background jobsfg %1 # bring job 1 to foregroundbg %1 # resume stopped job in backgroundCtrl+Z # suspend foreground job (SIGTSTP)nohup work?Answer: nohup runs a command immune to SIGHUP (sent when the controlling terminal closes). It also redirects stdout to nohup.out if stdout is a terminal. Combine with & to detach completely: nohup cmd &.
nice and renice do?Answer: nice sets the scheduling priority (niceness) when starting a process. Range: -20 (highest priority) to +19 (lowest). renice changes priority of a running process. Only root can set negative niceness.
xxxxxxxxxxnice -n 10 make # start with niceness 10renice -n 5 -p 1234 # change PID 1234 to niceness 5xxxxxxxxxxps aux # snapshot of all processesps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cputop / htop # interactive, real-time/proc filesystem?Answer: /proc is a virtual filesystem (procfs) that exposes kernel data structures as files. /proc/<pid>/ contains per-process info: cmdline, maps (memory maps), fd/ (open file descriptors), status, stat, smaps, environ. /proc/cpuinfo, /proc/meminfo, /proc/net/ expose system-wide info.
xxxxxxxxxxss -tlnp | grep :8080lsof -i :8080netstat -tlnp | grep :8080 # older systemsxxxxxxxxxxps -o ppid= -p <pid>cat /proc/<pid>/status | grep PPidpstree -p <pid>wait() and why is it important?Answer: wait() (and waitpid()) is a system call that blocks the parent until a child terminates, then retrieves the child's exit status. Without it, children become zombies. In shells, wait is also a built-in that waits for background jobs.
exec() family of calls.Answer: exec() replaces the current process image with a new program. Variants: execve(path, argv, envp) (the actual syscall), execvp (searches PATH), execle (explicit env), etc. The PID remains the same. Open file descriptors are inherited unless marked FD_CLOEXEC.
Answer: Virtual memory gives each process its own isolated address space, larger than physical RAM. The kernel maps virtual pages to physical frames via page tables. Benefits: isolation, ability to use more memory than physically available (swap), simpler program loading, shared libraries via shared mappings.
Answer: A virtual address is what the process sees — it's specific to the process's address space. The MMU (Memory Management Unit) translates it to a physical address using page tables. Multiple processes can have the same virtual address mapping to different physical frames.
Answer: From low to high (typical Linux x86-64):
Text segment — read-only executable code
Data segment — initialized global/static variables
BSS — uninitialized globals (zero-filled)
Heap — grows upward via brk()/mmap()
Memory-mapped region — files, shared libs, anonymous mappings
Stack — grows downward, local variables, return addresses
Kernel space — above the user-space/kernel split (not accessible from user space)
Answer: Occurs when a process accesses a virtual address not currently mapped to a physical frame. The CPU raises an exception, the kernel's page fault handler runs, and either:
Minor fault: page is in memory but not mapped (e.g., COW page, lazy allocation) — kernel maps it, no I/O.
Major fault: page must be read from disk (swap or file-backed) — slower, involves I/O.
Invalid fault: illegal access → SIGSEGV.
malloc and mmap for memory allocation?Answer: malloc is a C library function that manages a heap (typically via brk()/sbrk() for small allocations or mmap() for large ones). mmap() is a system call that maps files or anonymous memory directly into the address space — used for large allocations, file I/O, and shared memory. mmap gives kernel-managed pages; malloc gives library-managed blocks.
Answer: When the kernel cannot satisfy a memory allocation request and swap is exhausted, the Out-Of-Memory killer is invoked. It scores processes (based on memory usage, niceness, runtime) and terminates one to free memory. /proc/<pid>/oom_score shows the score; /proc/<pid>/oom_score_adj adjusts it (-1000 = never kill, +1000 = always kill first).
Answer: Swap is disk space used to hold pages evicted from RAM when physical memory is low. The kernel's page replacement algorithm (similar to LRU) selects victim pages. Swapping is slow (disk I/O) and degrades performance significantly. swapon/swapoff manage swap partitions/files.
Answer:
Stack: fixed size (set by ulimit -s), automatically managed (grows/shrinks with function calls), stores local variables and return addresses, very fast allocation/deallocation, thread-private.
Heap: dynamic size, manually managed (malloc/free or new/delete), can be fragmented, shared within a process across threads.
Answer: mmap() maps a file (or part of it) directly into the process's virtual address space. Reads/writes to that region translate to file I/O managed by the kernel's page cache. Advantages: avoids explicit read/write syscalls, allows multiple processes to share the same file pages, useful for large files and IPC.
brk() and mmap() for heap management?Answer: brk()/sbrk() adjusts the program break — the end of the data segment — to grow/shrink the heap contiguously. Efficient for small, sequential allocations. mmap() creates independent memory regions anywhere in the address space — preferred for large allocations (glibc uses mmap for >128KB by default) as it can be independently freed.
ulimit control?Answer: ulimit sets per-process resource limits enforced by the kernel:
-s — stack size
-n — max open file descriptors
-u — max user processes
-v — max virtual memory
-c — core dump size
Soft limits can be raised up to the hard limit by the user; hard limits require root to raise.
xxxxxxxxxxfree -h # RAM and swap usagecat /proc/meminfo # detailed memory statsvmstat -s # virtual memory statstop / htop # per-process and systemsmem -r # proportional set size (PSS)Answer:
VSZ (Virtual Size): total virtual address space of the process, including all mappings, whether in RAM or not.
RSS (Resident Set Size): physical RAM currently used by the process, including shared libraries.
PSS (Proportional Set Size): RSS but shared pages counted proportionally (divided by number of sharing processes). PSS gives a fairer picture of actual memory use.
Answer: Huge pages (2MB or 1GB on x86-64 vs default 4KB) reduce TLB pressure by covering more memory per TLB entry. Useful for workloads with large working sets (databases, HPC). Configured via /proc/sys/vm/nr_hugepages. Transparent Huge Pages (THP) automatically promote pages; can be configured via /sys/kernel/mm/transparent_hugepage/enabled.
Answer: The slab allocator (SLUB/SLOB/SLAB) manages kernel memory for frequently allocated objects (inodes, task structs, etc.). It pre-allocates slabs (groups of memory pages) for specific object sizes, avoiding fragmentation and reducing allocation overhead. cat /proc/slabinfo shows slab statistics.
Answer: Each file has three permission sets: owner (user), group, other. Each set has read (r=4), write (w=2), execute (x=1) bits. For directories: r=list contents, w=create/delete entries, x=traverse (cd into). Example: chmod 755 file = rwxr-xr-x.
Answer:
setuid (4xxx): when set on an executable, it runs with the file owner's effective UID (e.g., /usr/bin/passwd runs as root). On directories, has no standard effect.
setgid (2xxx): on executables, runs with the file's group. On directories, new files inherit the directory's group.
sticky bit (1xxx): on directories, prevents users from deleting files they don't own (e.g., /tmp).
Answer: The real UID is who you actually are (who launched the process). The effective UID is what the kernel checks for most permission decisions. They differ when a setuid program is running. A process can temporarily drop privileges by changing its effective UID back to real UID.
sudo work internally?Answer: The sudo binary is setuid root. When invoked, it runs as root (effective UID 0), checks /etc/sudoers to authorize the request, then calls setuid() to become the target user (or stays root) before exec()ing the requested command.
Answer: POSIX ACLs allow per-user and per-group permissions beyond the owner/group/other model. Managed with getfacl / setfacl. The effective mask limits ACL permissions. Extended attributes store ACL data in the filesystem.
Answer: A login shell reads /etc/profile and ~/.bash_profile (or ~/.profile). A non-login interactive shell reads ~/.bashrc. A login shell is started when you log in via terminal, SSH, or bash --login. bash -i starts an interactive non-login shell.
PATH variable and how does the shell use it?Answer: PATH is a colon-separated list of directories the shell searches for executables when a command is entered without an absolute path. The shell tries each directory left-to-right and uses the first match found. Built-ins and functions are checked before PATH.
source (.) and executing a script?Answer: Executing a script (./script.sh) runs it in a subshell — environment changes don't affect the parent. source script.sh (or . script.sh) runs the script in the current shell — variable assignments, cd, and function definitions persist in the current session.
Answer: Shell variables are local to the current shell process. Environment variables are exported (export VAR) and inherited by child processes. Use env or printenv to list environment variables; set lists all shell variables.
Answer: (1) Tokenization & parsing. (2) Alias expansion. (3) Command type check: function → built-in → hashed path → PATH search. (4) Variable/glob/brace expansion. (5) fork() + exec() (for external commands), or direct execution (for built-ins). (6) Parent shell waits for child (foreground) or continues (background).
Answer: Signals are software interrupts sent to a process to notify it of an event. Defined in <signal.h>. A process can install a handler (sigaction()), ignore a signal, or accept the default action (usually terminate, dump core, stop, or continue).
| Signal | Number | Default Action | Description |
|---|---|---|---|
| SIGHUP | 1 | Terminate | Terminal hangup / config reload |
| SIGINT | 2 | Terminate | Ctrl+C |
| SIGQUIT | 3 | Core dump | Ctrl+\ |
| SIGILL | 4 | Core dump | Illegal instruction |
| SIGSEGV | 11 | Core dump | Segmentation fault |
| SIGPIPE | 13 | Terminate | Write to broken pipe |
| SIGALRM | 14 | Terminate | Timer (alarm()) |
| SIGTERM | 15 | Terminate | Graceful termination request |
| SIGCHLD | 17 | Ignore | Child state changed |
| SIGSTOP | 19 | Stop | Cannot be caught/ignored |
sigprocmask()?Answer: A process can block signals using sigprocmask() — blocked signals are not delivered until unblocked. They remain pending. This is used to protect critical sections from asynchronous signal interruption. sigpending() reveals pending signals. Each thread has its own signal mask.
SA_RESTART in sigaction?Answer: When set, system calls interrupted by the signal are automatically restarted rather than returning EINTR. Without it, programs must handle EINTR from calls like read(), write(), select().
Answer: Signals SIGRTMIN–SIGRTMAX (34–64) are real-time signals. Unlike standard signals, they queue (multiple signals of the same number are not merged), carry data (siginfo_t), and are delivered in order of signal number. Used for precise asynchronous notification.
Answer: CFS is the default Linux scheduler for normal processes. It tracks each process's virtual runtime (vruntime) — the amount of CPU time received, weighted by priority. The process with the smallest vruntime is chosen next. A red-black tree orders runnable processes by vruntime, giving O(log N) pick-next. It aims for proportionally fair CPU allocation.
Answer:
SCHED_OTHER (CFS) — default, time-sharing
SCHED_BATCH — batch workloads, slightly worse wake-up latency
SCHED_IDLE — lowest priority, only runs when nothing else does
SCHED_FIFO — real-time, first-in first-out (no time slice)
SCHED_RR — real-time, round-robin with time slice
SCHED_DEADLINE — EDF (earliest deadline first) for deadline-constrained tasks
Answer: CPU affinity restricts which CPUs a process/thread may run on.
xxxxxxxxxxtaskset -c 0,1 ./program # start on CPUs 0 and 1taskset -cp 0,1 <pid> # change running processVia API: sched_setaffinity(). Used for performance (cache locality, NUMA) or isolation.
Answer: A context switch is the kernel saving the running process's CPU state (registers, program counter) and restoring another process's state. Costs: saving/restoring CPU state, TLB flush (if not using PCID), cache invalidation. Triggered by: time slice expiry, blocking syscall, higher-priority task waking up.
chrt used for?xxxxxxxxxxchrt -f -p 50 <pid> # set SCHED_FIFO priority 50chrt -r -p 50 <pid> # set SCHED_RR priority 50chrt -p <pid> # display scheduling policyAnswer:
BIOS/UEFI — firmware initializes hardware, selects boot device.
Bootloader (GRUB) — reads partition, loads kernel image and initrd.
Kernel init — decompresses self, initializes subsystems (memory, drivers), mounts initrd (initramfs).
initramfs — minimal root filesystem; loads drivers, mounts real root.
PID 1 (systemd/init) — first user-space process; starts services.
Runlevel/target — systemd activates units to reach default target (graphical.target or multi-user.target).
Answer: systemd is a parallel init system using dependency graphs and socket/D-Bus activation to start services concurrently. SysV init uses sequential numbered rc scripts. systemd uses unit files (.service, .socket, .timer); SysV uses shell scripts in /etc/init.d/. systemd tracks processes via cgroups; SysV cannot reliably track spawned children.
xxxxxxxxxxsystemctl start/stop/restart/status nginxsystemctl enable/disable nginx # enable at bootsystemctl list-units --type=servicejournalctl -u nginx -f # follow logssystemctl daemon-reload # reload unit filesinitramfs and why is it needed?Answer: initramfs (initial RAM filesystem) is a temporary root filesystem loaded into memory by the bootloader. It allows the kernel to load drivers (disk controllers, LVM, encrypted volumes) needed to mount the real root filesystem. Once the real root is mounted, the kernel pivot_root() or switch_root() to it.
| Runlevel | SysV | systemd target |
|---|---|---|
| 0 | Halt | poweroff.target |
| 1 | Single-user | rescue.target |
| 3 | Multi-user, no GUI | multi-user.target |
| 5 | Multi-user, GUI | graphical.target |
| 6 | Reboot | reboot.target |
Answer: TCP is connection-oriented, reliable (retransmission, ordering, flow control), and higher overhead. UDP is connectionless, unreliable (no retransmission, no ordering), lower overhead. TCP: HTTP, SSH, FTP. UDP: DNS, DHCP, video streaming, VoIP.
xxxxxxxxxxip addr show # modern (iproute2)ip link showifconfig # legacyxxxxxxxxxxping <host> # ICMP echotraceroute <host> # path and latencymtr <host> # combined ping+traceroutenc -zv <host> <port> # TCP port connectivitytelnet <host> <port> # simple TCP testnetstat/ss show?Answer: They display socket/connection state:
xxxxxxxxxxss -tlnp # listening TCP, with PIDss -anp # all socketsnetstat -rn # routing tabless -s # socket summaryiptables / nftables?Answer: Firewall and packet-filtering frameworks. iptables uses tables (filter, nat, mangle) with chains (INPUT, OUTPUT, FORWARD) and rules matched against packet headers. nftables is its successor with a unified framework and more efficient rule matching. firewalld and ufw are higher-level front-ends.
Answer: An integer index into a per-process table of open files. FD 0 = stdin, 1 = stdout, 2 = stderr. All I/O happens via FDs. open() returns FDs; dup2() duplicates them. /proc/<pid>/fd/ lists open FDs as symlinks.
Answer: A pipe is an in-kernel FIFO buffer (typically 64KB). pipe() syscall creates two FDs: read end and write end. In cmd1 | cmd2, the shell creates a pipe, forks two processes: cmd1 gets the write end as stdout, cmd2 gets the read end as stdin. The kernel buffers data between them.
lsof and what can it tell you?xxxxxxxxxxlsof -p <pid> # files opened by processlsof /dev/sda1 # processes using a devicelsof -i TCP:80 # processes using TCP port 80lsof +D /var/log # files in directoryTells you: file path, type (REG, DIR, CHR, FIFO, IPv4), FD number, PID, permissions.
awk in one paragraph.Answer: awk is a text-processing language that processes input line by line, splitting each into fields ($1, $2, ...) by FS (default: whitespace). Pattern–action pairs run when patterns match. Special patterns: BEGIN (before input), END (after input). Built-in variables: NR (line number), NF (field count), FS, RS (record separator). Example:
xxxxxxxxxxawk '{sum += $3} END {print sum}' file # sum column 3awk -F: '$3 > 1000 {print $1}' /etc/passwd # UIDs > 1000sed usage.Answer: sed is a stream editor that applies editing commands (substitute, delete, print, append) to each line:
xxxxxxxxxxsed 's/foo/bar/g' file # replace all foo with barsed -n '10,20p' file # print lines 10-20sed '/^#/d' file # delete comment linessed -i.bak 's/old/new/g' file # in-place with backupxxxxxxxxxxbash -c 'echo > /dev/tcp/host/port' && echo opennc -zv host portnmap -p port hostAnswer: A named pipe is a FIFO with a filesystem entry, created via mkfifo. Unlike anonymous pipes, it can be opened by unrelated processes (by name). Writes block until a reader opens it and vice versa. Used for communication between unrelated processes without a shared parent.
xxxxxxxxxxinotifywait -m /path # events via inotifytail -f /var/log/syslog # follow a filewatch -n 1 ls -la /path # periodic commandstrace and what does it output?Answer: strace traces system calls and signals made by a process. Output shows: syscall name, arguments, return value. Useful for debugging hangs, file access, permission issues, network calls.
xxxxxxxxxxstrace -p <pid> # attach to running processstrace -e openat,read ls /tmp # filter specific syscallsstrace -f ./program # follow forksstrace -tt ./prog # with timestampsAnswer:
One-time: at 2pm tomorrow (interactive) or echo "cmd" | at 14:00.
Recurring: crontab -e — cron syntax: min hour dom month dow cmd. Example: 0 2 * * * /backup.sh runs daily at 2 AM.
systemd timers (.timer units) are a modern alternative with more features.
Answer: A hard link is a directory entry pointing directly to an inode — multiple names for the same file data, same inode number, same device. Deleting one leaves data intact until all hard links are removed. Cannot cross filesystems or link directories (usually). A soft link (symlink) is a file containing a path — following it redirects to the target. Can cross filesystems, point to directories, and dangle (target deleted).
Answer: An inode is a data structure storing file metadata: permissions, owner/group, size, timestamps (atime, mtime, ctime), link count, and pointers to data blocks. Does NOT store the filename — that's in the directory entry. Every file and directory has an inode. stat file displays inode info; ls -i shows inode numbers.
Answer:
atime (access time): last time the file's data was read. Often disabled (noatime mount option) for performance.
mtime (modification time): last time the file's data content was modified.
ctime (change time): last time the inode metadata changed (permissions, owner, link count) — NOT creation time.
chroot and what is it used for?Answer: chroot changes the apparent root directory for a process and its children. Used for: security isolation (jails), system recovery (chroot into a broken system), build environments. Does not provide complete isolation — privileged processes can escape. Containers (namespaces) provide stronger isolation.
/etc/passwd and /etc/shadow?Answer: /etc/passwd stores user account info (username, UID, GID, home dir, shell) — world-readable. Originally stored password hashes in field 2, now replaced with x. /etc/shadow stores hashed passwords and aging policy — readable only by root. Separation prevents unprivileged users from obtaining hashes for offline cracking.
mount command do?Answer: mount attaches a filesystem (on a device or network path) to a directory (mount point) in the VFS tree. After mounting, files are accessible via the mount point. /etc/fstab defines persistent mounts; systemd can also manage mounts via .mount units.
df vs du?Answer:
df -h — reports filesystem-level disk space (total, used, available) per mounted filesystem.
du -sh /path — reports actual disk usage of files/directories by traversing the tree.
They may disagree: deleted files held open by processes free space per df but still show in du until closed.
xxxxxxxxxxfdisk /dev/sda # MBR partitionsgdisk /dev/sda # GPT partitionsparted /dev/sda # unified, supports bothlsblk # list block devicesblkid # show filesystem UUIDsAnswer: LVM (Logical Volume Manager) abstracts physical storage: Physical Volumes (PVs, e.g., /dev/sdb) → Volume Group (VG) → Logical Volumes (LVs, used as block devices). Benefits: resize volumes without repartitioning, snapshots, spanning across disks, thin provisioning.
Answer: Control Groups (cgroups) limit and monitor resource usage (CPU, memory, I/O, network) for groups of processes. Used by systemd, Docker, Kubernetes to enforce resource limits and accounting. v1 has per-subsystem hierarchies; v2 (unified hierarchy) is the modern standard.
Answer: Namespaces isolate specific kernel resources per group of processes. Types: PID (process IDs), mount (filesystem view), network (network interfaces), UTS (hostname), IPC (SysV IPC), user (UIDs), cgroup, time. Containers combine multiple namespaces + cgroups for lightweight isolation.
LD_PRELOAD and how can it be used?Answer: LD_PRELOAD is an environment variable that causes the dynamic linker to load specified shared libraries before all others. Functions in the preloaded library override those in later libraries. Used for: debugging (intercept malloc), testing (mock system calls), performance profiling. Ignored for setuid binaries for security.
Answer: Static linking copies all library code into the executable at build time — self-contained, no runtime library dependencies, larger binary. Dynamic linking references shared libraries (.so files) resolved at load time by ld.so — smaller binary, shared memory for library code across processes, but requires libraries at correct paths/versions (ldd shows dependencies).
ld.so) find shared libraries?Answer: Search order: DT_RPATH in ELF (deprecated), LD_LIBRARY_PATH, DT_RUNPATH in ELF, /etc/ld.so.cache (built from /etc/ld.so.conf), default paths (/lib, /usr/lib). Run ldconfig to rebuild the cache after installing libraries.
/proc/sys and how do you use it for tuning?Answer: /proc/sys/ exposes kernel parameters as files. Read/write them directly or use sysctl:
xxxxxxxxxxsysctl net.core.somaxconn # readsysctl -w net.core.somaxconn=1024 # set temporarilyecho 1024 > /proc/sys/net/core/somaxconnPersistent: add to /etc/sysctl.conf or /etc/sysctl.d/.
/sys filesystem (sysfs)?Answer: sysfs exposes the kernel's device model — devices, drivers, buses — as a virtual filesystem under /sys. Attributes (files) represent device properties and can be read/written to configure hardware. udev uses sysfs events for device management.
dmesg?Answer: dmesg prints the kernel ring buffer — messages from the kernel during boot and runtime (driver init, hardware errors, OOM events). Limited circular buffer. journalctl -k provides the same via systemd. Useful for diagnosing hardware issues and driver problems.
xxxxxxxxxxmodprobe module_name # load with dependenciesinsmod /path/to/module.ko # load without dependency resolutionlsmod # list loaded modulesrmmod module_name # unloadmodinfo module_name # module metadatasar and what can it monitor?Answer: sar (System Activity Reporter, part of sysstat) collects and reports system performance data: CPU, memory, disk I/O, network, paging, context switches. Data is logged periodically and can be replayed. Examples:
xxxxxxxxxxsar -u 1 5 # CPU usage every 1s, 5 timessar -r # memory statssar -b # I/O statssar -n DEV # network statsgrep, egrep, and fgrep?Answer: grep uses basic regular expressions (BRE). egrep (= grep -E) uses extended regular expressions (ERE) — supports +, ?, |, () without backslash. fgrep (= grep -F) treats the pattern as a literal fixed string — fastest, no regex interpretation.
chmod work with octal vs. symbolic notation?xxxxxxxxxxchmod 755 file # octal: owner=rwx, group=rx, other=rxchmod u+x,g-w file # symbolic: add x for user, remove w for groupchmod a=r file # all: read onlychmod o= file # remove all permissions from othersxxxxxxxxxxchown -R user:group /pathsudo vs su?Answer: su switches the current user (requires the target user's password). su - creates a login shell for that user. sudo runs a single command as another user (usually root) after authenticating as yourself, governed by /etc/sudoers. sudo provides better auditability and fine-grained control.
Answer: IPC mechanism using socket API but communicating within the kernel (no network stack). Faster than TCP loopback. Identified by filesystem path (e.g., /run/docker.sock). Support stream (SOCK_STREAM) and datagram (SOCK_DGRAM) modes. Used by databases, Docker, X11, systemd.
/etc/hosts and how is it used?Answer: /etc/hosts maps hostnames to IP addresses, consulted before DNS (by default, per /etc/nsswitch.conf). Used for local overrides, testing, or blocking domains. Format: IP hostname alias...
xxxxxxxxxxfind / -type f -size +100M -exec ls -lh {} \;du -ah / | sort -rh | head -20ncdu / # interactive ncurses disk usagersync and how does it differ from cp?Answer: rsync synchronizes files/directories, transferring only differences (delta). Supports remote transfer over SSH (rsync -avz src user@host:/dest), preserves permissions/timestamps/symlinks, resumes interrupted transfers. cp copies entirely each time.
xxxxxxxxxxiostat -x 1 # extended I/O stats per deviceiotop # per-process I/Odd if=/dev/zero of=test bs=1G count=1 oflag=direct # sequential write testhdparm -Tt /dev/sda # disk read speedscreen / tmux and why use it?Answer: Terminal multiplexers that keep sessions alive after disconnect. Multiple windows/panes in one terminal. Detach with Ctrl+a d (screen) or Ctrl+b d (tmux), reattach with screen -r / tmux attach. Essential for long-running remote tasks.
cron and how do you configure it?Answer: cron is a daemon that executes scheduled commands. crontab -e edits per-user crontabs. Syntax: min hour dom month dow command. Special strings: @reboot, @daily, @hourly. System-wide crontabs: /etc/crontab, /etc/cron.d/. Output is emailed unless redirected.
/tmp and /var/tmp?Answer: /tmp is cleared on reboot (often mounted as tmpfs in memory). /var/tmp persists across reboots. Applications needing temporary space that survives reboots should use /var/tmp.
xxxxxxxxxxuptimecat /proc/loadavgw # uptime + logged-in users + loadLoad average = average number of runnable + uninterruptible processes over 1, 5, 15 minutes. A load equal to the number of CPUs means fully utilized.
top's display tell you?Answer: Header: uptime, users, load averages. CPU line: %us (user), %sy (system/kernel), %ni (nice), %id (idle), %wa (iowait), %hi (hardware IRQ), %si (software IRQ), %st (steal, VM). Memory lines: total, free, used, buff/cache, swap. Process list: PID, user, priority, nice, VIRT, RES, SHR, state, %CPU, %MEM, TIME+, command.
ionice used for?xxxxxxxxxxionice -c3 -p <pid> # idle I/O class (lowest priority)ionice -c2 -n4 ./prog # best-effort, priority 4Sets I/O scheduling priority for a process using the CFQ/BFQ scheduler classes: real-time (1), best-effort (2), idle (3).
/proc/interrupts?Answer: Shows per-CPU interrupt counts for each IRQ line. Useful for diagnosing interrupt affinity issues and IRQ storms. Columns: IRQ number, per-CPU counts, type, device name.
syslog and how does logging work in Linux?Answer: syslog is a standard logging protocol. Traditionally, syslogd (or rsyslog, syslog-ng) receives log messages from applications (via /dev/log socket or UDP/TCP port 514) and routes them to files/remote hosts based on facility+priority rules. systemd uses journald (binary journal) with journalctl for querying.
/etc/resolv.conf?Answer: Configures DNS resolver: nameserver lines list DNS servers (up to 3), search sets domain search list, options for timeout/retries. On systems with systemd-resolved or NetworkManager, this file may be a symlink managed automatically.
xxxxxxxxxxlscpu # CPU infolsmem # memory rangeslspci # PCI deviceslsusb # USB devicesdmidecode # BIOS/hardware DMI datahwinfo # comprehensive hardware info/etc/fstab?Answer: Defines filesystems to mount at boot. Fields: device, mount point, filesystem type, options, dump (backup), pass (fsck order). Example:
xxxxxxxxxxUUID=abc123 / ext4 defaults 0 1tmpfs /tmp tmpfs nodev,nosuid,size=2G 0 0
sync and fsync?Answer: sync is a command/syscall that flushes all dirty kernel buffers to disk (writes are buffered for performance). fsync(fd) flushes buffers for a specific file to the storage device — needed for durability guarantees (databases). fdatasync() is like fsync but skips metadata updates not needed for data recovery.
xxxxxxxxxxltrace ./program # traces dynamic library callsltrace -p <pid> # attach to running processShows calls to libc and other shared library functions, unlike strace which shows kernel boundary calls.
perf used for?Answer: perf is the Linux performance analysis tool:
xxxxxxxxxxperf stat ./prog # hardware counters (cycles, cache misses)perf top # live function-level hotspotsperf record ./prog # record samplesperf report # analyze recorded samplesperf trace ./prog # like strace but lower overheadgdb to debug a crash?xxxxxxxxxxgdb ./program core # analyze core dumpgdb ./program # run and debug(gdb) run # start program(gdb) bt # backtrace on crash(gdb) info locals # local variables(gdb) p variable # print value(gdb) break func # set breakpoint(gdb) attach <pid> # attach to running processvalgrind and when is it useful?Answer: valgrind is a dynamic analysis tool suite. memcheck (default) detects memory errors: heap overflows, use-after-free, uninitialized reads, memory leaks. massif profiles heap usage. callgrind profiles CPU. Runs programs on a synthetic CPU — significant slowdown (~10–50×). Used in development/testing, not production.
Answer: A core dump is a file containing the memory image of a process at crash time. Enable:
xxxxxxxxxxulimit -c unlimited # allow core dumps in current shellecho /tmp/core.%p > /proc/sys/kernel/core_patternAnalyze with gdb ./binary core. systemd-coredump manages core dumps via coredumpctl.
netcat (nc) used for in system administration?xxxxxxxxxxnc -l 8080 # listen on port 8080nc host 8080 # connectnc -zv host 22 # port scancat file | nc host 9999 # transfer filenc -l 9999 > received_file # receive filetcpdump used for?xxxxxxxxxxtcpdump -i eth0 port 80 # capture HTTP on eth0tcpdump -w capture.pcap # save to filetcpdump -r capture.pcap # read filetcpdump host 10.0.0.1 # filter by hosttcpdump -nn -i any # all interfaces, numeric/dev/random vs /dev/urandom?Answer: Both provide cryptographically secure random numbers from the kernel's entropy pool. /dev/random blocks when entropy is exhausted (older kernels). /dev/urandom never blocks — it uses the CSPRNG which is safe post-seeding. On modern Linux (≥5.18), both behave identically after boot. Use getrandom() syscall for applications.
watch command?xxxxxxxxxxwatch -n 2 df -h # run df -h every 2 secondswatch -d 'ps aux | head' # highlight differencesAnswer: /proc/sys/ changes are volatile (lost on reboot). Persistent changes go in /etc/sysctl.conf or files under /etc/sysctl.d/. Apply immediately with sysctl -p. Verify: sysctl <key>.
namespaces and how do they enable containerization?Answer: Linux namespaces create isolated views of kernel resources. A container typically uses: PID namespace (isolated process tree), mount namespace (own filesystem), network namespace (own interfaces/routing), UTS (own hostname), IPC, user (UID mapping). unshare and clone() with flags create new namespaces. The container runtime (Docker/containerd) wires these together.
strace's overhead concern in production?Answer: strace uses ptrace() which serializes all syscalls through the tracer — can slow a process 2–10×. For production tracing, use bpftrace or perf trace which use eBPF with much lower overhead.
Answer: Extended Berkeley Packet Filter is a safe in-kernel virtual machine that runs user-supplied programs at kernel events (syscalls, tracepoints, kprobes, network packets) without modifying kernel source or loading modules. Used for: observability (bpftrace, bcc tools), networking (XDP), security (seccomp-bpf, Falco). Programs are JIT-compiled and verified for safety.
auditd used for?Answer: auditd is the Linux audit daemon that records security-relevant events (file access, syscalls, logins, privilege changes) to /var/log/audit/audit.log. Rules set via auditctl. ausearch and aureport query logs. Required for compliance (PCI-DSS, SOX).
adduser and useradd?Answer: useradd is the low-level binary (sets specific options). adduser is a higher-level Perl/shell script (Debian/Ubuntu) that calls useradd with sane defaults, creates home directory, sets shell, prompts for password. On RHEL/CentOS, adduser is a symlink to useradd.
xxxxxxxxxx# Debian/Ubuntu:dpkg -S /usr/bin/vimapt-file search vim
# RHEL/CentOS:rpm -qf /usr/bin/vimyum/dnf provides vimsystemd-analyze used for?xxxxxxxxxxsystemd-analyze # total boot timesystemd-analyze blame # per-unit startup timesystemd-analyze critical-chain # critical pathsystemd-analyze plot > boot.svg # graphical timelinejournalctl and how do you use it?xxxxxxxxxxjournalctl -u nginx # logs for nginx servicejournalctl -f # follow (like tail -f)journalctl -b # current bootjournalctl -b -1 # previous bootjournalctl --since "1 hour ago"journalctl -p err # error priority and abovejournalctl -k # kernel messages/etc/sudoers and how do you edit it safely?Answer: /etc/sudoers defines who can run what as whom with sudo. Always edit with visudo (validates syntax before saving — a syntax error can lock out all sudo access). Key syntax: user host=(runas) command. Includes: %wheel ALL=(ALL) ALL (wheel group gets full sudo), NOPASSWD: for passwordless commands.
Answer: A memory leak occurs when allocated memory is never freed, causing the process's memory usage to grow indefinitely. Detection methods:
xxxxxxxxxxvalgrind --leak-check=full ./prog # find leaks at exit/proc/<pid>/status | grep VmRSS # watch RSS grow over timesmem -p # proportional memory usagepmap -x <pid> # memory mapaddress sanitizer: gcc -fsanitize=address # compile-time instrumentation