Interview Q&A Linux All Levels

Linux Interview Questions & Answers (2026) Part 01

40+ Linux interview questions and answers covering processes, file system, permissions, services, and troubleshooting — Basic to Advanced.

April 26, 2025 24 min read 48 Questions DB
48 Total Questions
24 Basic
21 Intermediate
3 Advanced
Level:
Q1
Explain the booting process of Linux.
Basic

Ans:

  1. BIOS/UEFI - Hardware runs Power-On Self Test (POST). BIOS/UEFI finds the bootable device.
  2. MBR/GPT - Master Boot Record (first 512 bytes of disk) or GPT partition table is read. Bootloader location is found.
  3. GRUB2 (Bootloader) - GRUB2 loads the Linux kernel (vmlinuz) and initial RAM disk (initrd/initramfs) into memory.
  4. Kernel Initialization - Kernel decompresses itself, initializes hardware drivers, mounts the root filesystem.
  5. initramfs - Temporary root filesystem used to load necessary drivers before the real root is mounted.
  6. systemd (PID 1) - The first process started by the kernel. It reads unit files and brings up the system.
  7. Targets - systemd reaches the configured target (e.g., multi-user.target or graphical.target), starting all required services.
  8. Login prompt - Finally, a TTY login prompt or display manager appears.
# View boot messages
journalctl -b

# View systemd target
systemctl get-default
Q2
What are services in Linux?
Basic

Ans:

A service is a background process (daemon) managed by systemd. Services start automatically at boot and run without user interaction.

  • Unit files define services and are located in /etc/systemd/system/ or /lib/systemd/system/
  • Common commands:
# Check status of a service
systemctl status nginx

# Start / Stop / Restart a service
systemctl start nginx
systemctl stop nginx
systemctl restart nginx

# Enable service at boot
systemctl enable nginx

# List all running services
systemctl list-units --type=service --state=running
Q3
How do you check open ports in Linux?
Basic

Ans:

# Using ss (recommended, modern)
ss -tulnp

# Using netstat (older systems)
netstat -tulnp

# Using lsof
lsof -i -P -n

# Check if a specific port is open
ss -tulnp | grep :80

# Using nmap (scan remotely)
nmap -p 80,443 <server-ip>

Flag meanings for ss/netstat:

  • -t - TCP
  • -u - UDP
  • -l - Listening only
  • -n - Show numeric ports (no DNS resolution)
  • -p - Show process name/PID
Q4
Explain the Linux file system structure.
Basic

Ans:

DirectoryPurpose
/Root of the entire filesystem
/binEssential user binaries (ls, cp, mv)
/sbinSystem binaries (for root/admin)
/etcConfiguration files
/homeUser home directories
/varVariable data — logs, spools, temp files
/tmpTemporary files (cleared on reboot)
/usrUser programs and libraries
/optOptional third-party software
/procVirtual filesystem — kernel/process info
/devDevice files (disks, terminals)
/mnt / /mediaMount points for external/removable drives
/bootKernel and bootloader files
# View tree structure
ls /

# Check filesystem type
df -Th
Q5
What is the command to check OS version in Linux?
Basic

Ans:

# Most universal
cat /etc/os-release

# For RHEL/CentOS
cat /etc/redhat-release

# For Debian/Ubuntu
cat /etc/debian_version

# Kernel version
uname -r

# All system info
uname -a

# Using lsb_release
lsb_release -a
Q6
What is a process in Linux?
Basic

Ans:

A process is a running instance of a program. Every process has:

  • A unique PID (Process ID)
  • A PPID (Parent Process ID)
  • An owner (UID)
  • A state (Running, Sleeping, Zombie, Stopped)
# List all processes
ps aux

# Tree view showing parent-child
pstree

# Dynamic real-time view
top
htop
Q7
What is a daemon in Linux?
Basic

Ans:

A daemon is a background process that runs continuously without user interaction. Daemons usually:

  • Start at boot
  • Have names ending in d (e.g., sshd, httpd, crond)
  • Run as root or a dedicated service user
# List daemons managed by systemd
systemctl list-units --type=service

# Check if sshd is running
systemctl status sshd
Q8
What are the different commands to check running processes?
Basic

Ans:

# Static snapshot
ps aux            # All processes with details
ps -ef            # Full format listing
ps -u username    # Processes for a specific user

# Dynamic / real-time
top               # Interactive, updates every 3s
htop              # Colored, more user-friendly (install separately)

# Tree format
pstree            # Parent-child hierarchy

# Filter specific process
ps aux | grep nginx
pgrep nginx
Q9
What is the meaning of `ps`? Can we get dynamic output from the ps command?
Basic

Ans:

ps stands for Process Status. It takes a snapshot of currently running processes at that moment. It is not dynamic.

For dynamic/real-time output, use:

# Real-time with auto-refresh every 2 seconds
watch -n 2 ps aux

# Or use top/htop for true dynamic view
top
htop
Q10
What are the fields in top and ps commands?
Basic

Ans:

top fields:

FieldMeaning
PIDProcess ID
USEROwner of process
PRPriority
NINice value
VIRTVirtual memory used
RESResident (physical) memory
SHRShared memory
SState (R=running, S=sleeping, Z=zombie)
%CPUCPU usage
%MEMMemory usage
TIME+Total CPU time
COMMANDProcess name

ps aux fields:

FieldMeaning
USERProcess owner
PIDProcess ID
%CPUCPU usage
%MEMMemory usage
VSZVirtual memory size
RSSResident memory size
TTYTerminal associated
STATProcess state
STARTStart time
TIMECPU time consumed
COMMANDCommand that started it
Q11
How to check load average in Linux?
Basic

Ans:

Load average shows how many processes are waiting to run (averaged over 1, 5, and 15 minutes).

# Using uptime
uptime
# Output: 10:30  up 5 days,  load average: 0.45, 0.60, 0.55

# Using top (first line)
top

# From /proc
cat /proc/loadavg

# Using w command
w

Interpretation: If load average > number of CPU cores, system is overloaded.

# Check number of CPU cores
nproc
cat /proc/cpuinfo | grep processor | wc -l
Q12
What are the different states of a process?
Basic

Ans:

StateSymbolMeaning
RunningRActively using CPU or in run queue
Sleeping (interruptible)SWaiting for an event, can be interrupted
Sleeping (uninterruptible)DWaiting for I/O, cannot be interrupted
StoppedTPaused (Ctrl+Z or SIGSTOP)
ZombieZFinished but not reaped by parent
IdleIKernel idle thread
Q13
How to kill a foreground process?
Basic

Ans:

# While process is running in terminal:
Ctrl + C    # Sends SIGINT — graceful interrupt

Ctrl + Z    # Sends SIGTSTP — suspends (pauses) it

# If you know the PID
kill -15 <PID>   # SIGTERM — graceful termination
kill -9 <PID>    # SIGKILL — force kill (cannot be caught)
Q14
How to kill a background process?
Basic

Ans:

# Find the PID
ps aux | grep process_name
pgrep process_name

# Kill by PID
kill <PID>          # SIGTERM (graceful)
kill -9 <PID>       # SIGKILL (force)

# Kill by name
pkill nginx
killall nginx

# If started with & and you know job number
jobs               # List background jobs
kill %1            # Kill job number 1
Q15
How to bring a background process to the foreground?
Basic

Ans:

# Step 1: See background jobs
jobs
# Output: [1]+  Stopped    ./script.sh

# Step 2: Bring to foreground
fg %1      # Bring job 1 to foreground

# Or resume a stopped process in background
bg %1      # Resume job 1 in background
Q16
What is difference between htop and top?
Basic

Ans:

Featuretophtop
InterfaceText-based, minimalColor-coded, visual
Mouse supportNoYes
Kill processVia key commandsClick or F9
ScrollLimitedHorizontal + vertical
CPU per coreNo (combined)Yes (individual bars)
Tree viewNoYes (F5)
InstallationBuilt-inNeeds install (apt/yum install htop)
Q17
What is difference between ps and top?
Basic

Ans:

Featurepstop
OutputStatic snapshotDynamic, real-time
UpdatesOne-timeContinuous (every 3s)
Use caseScripting, loggingLive monitoring
InteractivityNoneKill, renice, filter
Resource usageMinimalSlightly higher
ps aux | grep nginx    # Check if nginx is running (static)
top                    # Monitor all processes live
Q18
How do you verify file ownership and permissions?
Basic

Ans:

# Long listing format — shows permissions, owner, group
ls -la /path/to/file

# Detailed stat output
stat /path/to/file

# Example output of ls -la:
# -rw-r--r-- 1 ec2-user ec2-user 1234 Apr 26 10:00 myfile.txt
# ^type+perms  ^owner   ^group

# Permission breakdown:
# r=4, w=2, x=1
# 755 = rwxr-xr-x (owner:rwx, group:r-x, others:r-x)
# 644 = rw-r--r-- (owner:rw-, group:r--, others:r--)
Q19
How do you check sudo privileges of a user?
Basic

Ans:

# Check what sudo commands a user can run
sudo -l                    # For current user
sudo -l -U username        # For another user (as root)

# View sudoers file
sudo cat /etc/sudoers
sudo visudo               # Safe edit with syntax check

# Check if user is in sudo/wheel group
groups username
id username
getent group sudo          # Debian/Ubuntu
getent group wheel         # RHEL/CentOS
Q20
How do you give only read-only access to a file?
Basic

Ans:

# Remove write permissions for everyone
chmod a-w filename

# Set read-only for owner only
chmod 400 filename      # r--------

# Read for owner and group, no write
chmod 440 filename      # r--r-----

# Read for all, no write for anyone
chmod 444 filename      # r--r--r--

# Make immutable (even root can't write without removing flag)
sudo chattr +i filename
lsattr filename         # Verify immutable flag
Q21
How do you check free space inside a specific folder?
Basic

Ans:

# Disk usage of a folder (human-readable)
du -sh /var/log/

# Show all subdirectory sizes
du -h /var/log/

# Sort by size, show top 10 folders
du -h /var/ | sort -rh | head -10

# Check overall disk space
df -h

# Check inode usage (another type of "space")
df -i
Q22
What is a zombie process? Can we create one?
Intermediate

Ans:

A zombie process is a process that has finished execution but its entry still exists in the process table because the parent hasn’t called wait() to read the exit status.

  • Zombie processes consume no CPU or memory — just a PID slot
  • They appear as state Z in ps
# Find zombie processes
ps aux | grep 'Z'
# or
ps -el | grep zombie

Creating a zombie (C example concept):

// Child exits, parent sleeps without wait() → zombie created
if (fork() == 0) { exit(0); }  // child exits
else { sleep(60); }             // parent doesn't call wait()

How to remove zombies:

  • Kill or restart the parent process — the zombie is then adopted by init/systemd which cleans it up
Q23
Where does the PID get stored in Linux?
Intermediate

Ans:

  • PIDs are tracked by the kernel in the process table (in kernel memory)
  • For many services, the PID is written to a PID file on disk
# Common PID file locations
/var/run/nginx.pid
/var/run/sshd.pid
/run/<service>.pid

# Read a PID file
cat /var/run/nginx.pid

# From /proc filesystem (virtual, kernel-managed)
ls /proc/          # Each numbered directory = a PID
cat /proc/1234/status   # Details of PID 1234
Q24
A service like httpd is running in the foreground. How do you shift it to the background?
Intermediate

Ans:

# Method 1: Suspend then background
Ctrl + Z          # Suspend the foreground process
bg %1             # Resume it in background

# Method 2: Start it with & from the beginning
httpd &

# Method 3: Use nohup to persist after terminal closes
nohup httpd &

# Method 4: Use disown to detach from shell
httpd &
disown %1

# Best practice: Use systemd
systemctl start httpd    # systemd manages it as a daemon
Q25
What is the difference between terminating, killing, and stopping a process?
Intermediate

Ans:

ActionSignalMeaning
TerminateSIGTERM (15)Politely ask process to stop. Process can catch it and clean up.
KillSIGKILL (9)Immediately destroy the process. Cannot be caught or ignored.
StopSIGSTOP (19)Pause/suspend the process. It stays in memory but doesn’t run.
ContinueSIGCONT (18)Resume a stopped process.
kill -15 <PID>   # Terminate (graceful)
kill -9  <PID>   # Kill (force)
kill -19 <PID>   # Stop
kill -18 <PID>   # Continue
Q26
Which kill signal is best and why?
Intermediate

Ans:

SIGTERM (15) is the best choice in most cases because:

  • It asks the process to cleanly shut down
  • The process can save state, close connections, and release resources
  • It avoids data corruption
kill -15 <PID>   # Preferred
# or simply
kill <PID>       # SIGTERM is the default

Only use SIGKILL (9) when a process is unresponsive to SIGTERM:

kill -9 <PID>    # Last resort — no cleanup, risk of data loss

Recommended approach:

kill -15 <PID>          # Try graceful first
sleep 5
kill -0 <PID> && kill -9 <PID>   # Force kill only if still alive
Q27
A process is consuming high CPU and memory. How do you manage it?
Intermediate

Ans:

# Step 1: Identify the culprit
top              # Press P to sort by CPU, M for memory
htop             # More visual, filter-friendly

# Step 2: Get the PID
ps aux --sort=-%cpu | head -10   # Top CPU consumers
ps aux --sort=-%mem | head -10   # Top memory consumers

# Step 3: Investigate
ls -la /proc/<PID>/exe           # What binary is it?
cat /proc/<PID>/status           # Detailed info
lsof -p <PID>                    # Files it has open

# Step 4: Reduce priority (if you can't kill it)
renice +10 <PID>                 # Lower priority (nicer = less CPU)

# Step 5: Kill if necessary
kill -15 <PID>    # Graceful
kill -9  <PID>    # Force
Q28
Do you know about htop, iotop, iostat, vmstat?
Intermediate

Ans:

htop - Enhanced top with colors, mouse support, easy kill/nice controls

htop

iotop - Shows disk I/O usage per process (like top but for disk)

sudo iotop
sudo iotop -o    # Only show processes doing I/O

iostat - Reports CPU and disk I/O statistics

iostat           # One-time snapshot
iostat -x 2 5   # Extended stats, every 2s, 5 times

vmstat - Reports virtual memory, processes, CPU stats

vmstat           # One-time
vmstat 2 5      # Every 2 seconds, 5 iterations
# Fields: r=run queue, b=blocked, swpd, free, buff, cache, si, so, bi, bo, in, cs, us, sy, id, wa
Q29
How do you fix 'Permission Denied' errors on EC2?
Intermediate

Ans:

# Step 1: Check permissions of the file/directory
ls -la /path/to/file

# Step 2: Check current user
whoami
id

# Step 3: Check file ownership
stat /path/to/file

# Step 4: Fix ownership (if you have sudo)
sudo chown ec2-user:ec2-user /path/to/file

# Step 5: Fix permissions
sudo chmod 755 /path/to/directory
sudo chmod 644 /path/to/file

# Step 6: For SSH key permission denied
chmod 400 ~/.ssh/my-key.pem       # Key must be owner-read only
chmod 700 ~/.ssh/                  # .ssh dir must be 700
chmod 600 ~/.ssh/authorized_keys   # authorized_keys must be 600

# Step 7: Check SELinux/AppArmor if applicable
getenforce                         # Check SELinux status
sestatus
Q30
How do you change directory ownership for Jenkins deployments?
Intermediate

Ans:

# Change owner to jenkins user
sudo chown -R jenkins:jenkins /var/lib/jenkins/workspace/

# Change owner of deployment directory
sudo chown -R jenkins:jenkins /opt/myapp/

# Give jenkins write permissions
sudo chmod -R 755 /opt/myapp/

# Verify
ls -la /opt/myapp/

# If Jenkins needs to run as root occasionally, add to sudoers:
sudo visudo
# Add: jenkins ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp
Q31
How do you identify files recently modified by the root user?
Intermediate

Ans:

# Files modified in last 24 hours owned by root
find / -user root -mtime -1 2>/dev/null

# Files modified in last 60 minutes
find /etc -user root -mmin -60

# Files changed recently (any user) with timestamps
find /var/log -newer /tmp/reference_file -ls

# Check audit logs for root activity (if auditd is running)
ausearch -ua root -ts today

# Check bash history for root
sudo cat /root/.bash_history

# Check last logins
last root
Q32
How do you check which user modified a file last?
Intermediate

Ans:

# Check last modification time (but not which user)
stat filename
ls -la filename

# To track WHO modified — use auditd
# Install and enable auditd
sudo systemctl start auditd

# Add a watch rule on the file
sudo auditctl -w /path/to/file -p wa -k file_watch

# Search audit logs for that file
sudo ausearch -f /path/to/file

# Alternative: Check /var/log/auth.log or /var/log/secure
grep "filename" /var/log/auth.log

Note: Linux doesn’t natively record which user last modified a file without auditd. stat only shows timestamps.

Q33
How do you allow a non-root user to run Docker commands?
Intermediate

Ans:

# Add user to the docker group
sudo usermod -aG docker username

# Apply group change (user must log out and log back in, or:)
newgrp docker

# Verify
docker ps        # Should work without sudo
groups           # Should show 'docker' in list

# Alternative: Use sudo for specific docker commands in sudoers
sudo visudo
# Add: username ALL=(ALL) NOPASSWD: /usr/bin/docker

Security note: The docker group gives root-equivalent access. Use carefully.

Q34
How do you troubleshoot high CPU usage in an EC2 instance?
Intermediate

Ans:

# Step 1: Identify top CPU-consuming process
top             # Press P to sort by CPU
htop

# Step 2: Get details on the process
ps aux --sort=-%cpu | head -10
lsof -p <PID>   # What files/connections it uses

# Step 3: Check system-wide load
uptime
vmstat 1 5      # CPU wait, idle, system time

# Step 4: Check for CPU steal (in VMs)
top             # %st column = CPU stolen by hypervisor

# Step 5: Check recent deployments or cron jobs
journalctl -xe
crontab -l
cat /var/log/cron

# Step 6: Resolve
renice +10 <PID>    # Reduce priority
kill -15 <PID>      # Terminate if rogue process
Q35
How do you archive old log files automatically?
Intermediate

Ans:

Method 1: logrotate (recommended)

# Configure logrotate
sudo nano /etc/logrotate.d/myapp

# Example config:
/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0644 appuser appuser
    postrotate
        systemctl reload myapp
    endscript
}

# Test the config
sudo logrotate -d /etc/logrotate.d/myapp

# Force run
sudo logrotate -f /etc/logrotate.d/myapp

Method 2: Cron + tar

# Add to crontab: archive logs older than 7 days
crontab -e

# Daily at midnight, compress logs older than 7 days
0 0 * * * find /var/log/myapp -name "*.log" -mtime +7 -exec gzip {} \;
Q36
How do you check system logs for EC2 boot errors?
Intermediate

Ans:

# View full boot log for current boot
journalctl -b

# View previous boot log
journalctl -b -1

# Filter for errors only
journalctl -b -p err

# Check kernel ring buffer
dmesg
dmesg | grep -i error
dmesg | grep -i fail

# Traditional log files
cat /var/log/messages       # RHEL/CentOS
cat /var/log/syslog         # Debian/Ubuntu
cat /var/log/boot.log

# EC2 Console Output (from AWS Console)
# Go to: EC2 → Instance → Actions → Monitor and troubleshoot → Get system log
Q37
How do you troubleshoot slow SSH connections to EC2?
Intermediate

Ans:

# Step 1: Test with verbose output to see where it hangs
ssh -vvv -i key.pem ec2-user@<ip>

# Step 2: Check DNS resolution (common cause of slow SSH)
# On the server, edit /etc/ssh/sshd_config:
UseDNS no

# Step 3: Check GSSAPI authentication
# In /etc/ssh/sshd_config:
GSSAPIAuthentication no

# Step 4: Restart sshd after changes
sudo systemctl restart sshd

# Step 5: Check security group allows port 22 from your IP
# In AWS Console: Security Group → Inbound rules → Port 22

# Step 6: Check server load
uptime
top
Q38
How do you schedule EC2 instances to stop/start automatically using cron?
Intermediate

Ans:

Method 1: AWS Instance Scheduler (managed service)

Method 2: Lambda + EventBridge (CloudWatch Events)

# Create Lambda to start/stop instance
# EventBridge Rule: cron(0 8 * * ? *)  → start at 8 AM UTC
# EventBridge Rule: cron(0 20 * * ? *) → stop at 8 PM UTC

Method 3: AWS CLI in cron on a management server

# On a management EC2, edit crontab
crontab -e

# Stop instance at 8 PM UTC
0 20 * * * aws ec2 stop-instances --instance-ids i-1234567890abcdef0 --region us-east-1

# Start instance at 8 AM UTC
0 8 * * * aws ec2 start-instances --instance-ids i-1234567890abcdef0 --region us-east-1
Q39
How do you sync data between two EC2 instances?
Intermediate

Ans:

# Method 1: rsync (most efficient — only transfers changes)
rsync -avz -e "ssh -i key.pem" /local/path/ ec2-user@<dest-ip>:/remote/path/

# Method 2: scp (simple copy)
scp -i key.pem -r /source/ ec2-user@<dest-ip>:/destination/

# Method 3: rsync in cron for periodic sync
crontab -e
*/15 * * * * rsync -avz /data/ ec2-user@<dest-ip>:/data/ >> /var/log/sync.log 2>&1

# Method 4: Use S3 as intermediary
aws s3 sync /data/ s3://my-bucket/data/
# On destination:
aws s3 sync s3://my-bucket/data/ /data/
Q40
How do you back up EC2 files to an S3 bucket?
Intermediate

Ans:

# Method 1: AWS CLI sync
aws s3 sync /var/www/html/ s3://my-backup-bucket/webfiles/

# With date-stamped backup
aws s3 cp /var/log/ s3://my-backup-bucket/logs/$(date +%Y-%m-%d)/ --recursive

# Method 2: Cron-based backup
crontab -e
0 2 * * * aws s3 sync /data/ s3://my-backup-bucket/data/ --delete >> /var/log/backup.log 2>&1

# Method 3: Tar + upload
tar -czf /tmp/backup-$(date +%Y%m%d).tar.gz /data/
aws s3 cp /tmp/backup-$(date +%Y%m%d).tar.gz s3://my-backup-bucket/

# Ensure EC2 has IAM role with s3:PutObject permission
aws sts get-caller-identity    # Confirm identity/role
Q41
How do you check disk I/O performance on EC2?
Advanced

Ans:

# Real-time I/O per process
sudo iotop -o

# Device-level I/O stats
iostat -x 2 5
# Look for: %util (device saturation), await (I/O wait time ms), r/s, w/s

# Check I/O wait in top
top
# %wa column = CPU time waiting for I/O

# Use vmstat for block I/O
vmstat 2 5
# bi = blocks in (reads), bo = blocks out (writes)

# Check specific disk
iostat -x sda 2 5

# AWS-specific: Check EBS CloudWatch metrics
# Metrics: VolumeReadOps, VolumeWriteOps, VolumeQueueLength
Q42
There is an sshd process taking high CPU and you don't have rights to kill it. What do you do?
Advanced

Ans:

# Step 1: Confirm it's actually high CPU
top -p $(pgrep sshd | head -1)

# Step 2: Try to renice (lower CPU priority) — may work without root
renice +19 <PID>

# Step 3: Investigate connections before escalating
ss -anp | grep sshd           # Check active connections
who                            # Who is logged in
last                           # Recent logins

# Step 4: Escalate to admin/ops team with evidence
# Provide: PID, CPU%, user, open connections

# Step 5: If you have sudo for systemctl only:
sudo systemctl restart sshd   # Restart the service gracefully

# Step 6: Report through incident management process
# Document: time, PID, CPU%, connections observed, action taken
Q43
Can you tell me what is hard link and soft link?
Basic

Ans:

Both let you have multiple “names” for a file, but they work very differently under the hood:

AspectHard LinkSoft Link (Symlink)
What it points toThe same inode (actual data on disk)The path/filename of the target
Crosses filesystems?No — must be on the same filesystemYes
Can link a directory?No (in most systems)Yes
If original is deletedData still accessible — link IS the dataBroken (“dangling”) link — points to nothing
ls -l showsSame inode number as original, no arrowlink -> target with an arrow, different inode
# Create a hard link — both names point to the same inode
ln original.txt hardlink.txt
ls -i original.txt hardlink.txt   # same inode number

# Create a soft (symbolic) link — points to the path
ln -s original.txt softlink.txt
ls -l softlink.txt                # softlink.txt -> original.txt

# Delete the original:
rm original.txt
cat hardlink.txt   # Still works — data isn't gone, inode still has a reference
cat softlink.txt   # "No such file or directory" — the path it pointed to is gone

When to use which: symlinks for pointing to configs/binaries across directories or filesystems (e.g., /etc/nginx/sites-enabled/ symlinking to sites-available/); hard links rarely used directly, but this is exactly the mechanism tools like rsync --link-dest use for space-efficient incremental backups.

Q44
Can you write a rule for setting iptables in Linux?
Intermediate

Ans:

# View current rules with line numbers
sudo iptables -L -n -v --line-numbers

# Allow inbound SSH (port 22) from a specific trusted IP only
sudo iptables -A INPUT -p tcp -s 203.0.113.10 --dport 22 -j ACCEPT

# Allow inbound HTTP/HTTPS from anywhere
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow already-established connections (return traffic) — critical, or replies get dropped
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow loopback traffic (localhost)
sudo iptables -A INPUT -i lo -j ACCEPT

# Block a specific malicious IP entirely
sudo iptables -A INPUT -s 198.51.100.20 -j DROP

# Default deny everything else inbound (set this LAST, after allow rules)
sudo iptables -A INPUT -j DROP

# Persist rules across reboots (Ubuntu/Debian)
sudo apt install iptables-persistent
sudo netfilter-persistent save

Key gotcha: rules are evaluated top to bottom, first match wins — a default-DROP rule added too early will block everything below it, including your own SSH access. Always test iptables changes over a console/serial connection (not just SSH) in case you lock yourself out.

Q45
I want to give a user execute permission for a file. Tell me how you do it.
Basic

Ans:

# Give the FILE OWNER execute permission (symbolic mode — additive, safe)
chmod u+x script.sh

# Give a SPECIFIC user (not the owner) execute permission via ACLs
sudo setfacl -m u:john:x script.sh
getfacl script.sh   # verify

# Give the file's GROUP execute permission
chmod g+x script.sh

# Give EVERYONE execute permission
chmod +x script.sh
# equivalent to: chmod a+x script.sh (a = all: owner+group+others)

# Numeric (absolute) mode — sets ALL permission bits explicitly, not additive
chmod 755 script.sh
# 7 (owner: rwx) 5 (group: r-x) 5 (others: r-x)

# Verify the result
ls -l script.sh
# -rwxr-xr-x  1 user  group  1024 Jan 1 10:00 script.sh

Symbolic (u+x) vs numeric (755) mode: prefer symbolic when you only want to add one permission without touching the others already set; use numeric when you want to set the complete permission state explicitly in one command.

Q46
Can you create an empty file with 100MB size?
Basic

Ans:

# Method 1: fallocate — fastest, allocates disk blocks instantly (no actual writing)
fallocate -l 100M testfile.img

# Method 2: dd — writes real data, slower but works on filesystems fallocate doesn't support
dd if=/dev/zero of=testfile.img bs=1M count=100
# bs=1M (block size) × count=100 = 100 MB

# Method 3: truncate — creates a "sparse" file; looks like 100MB but consumes
# almost no real disk space until data is actually written to it
truncate -s 100M testfile.img

# Verify the size
ls -lh testfile.img
du -h testfile.img   # actual disk usage — may differ from ls size for sparse files!

Difference to know for an interview: fallocate/dd reserve real disk blocks immediately; truncate creates a sparse filels -lh reports 100M, but du -h may report far less, since blocks are only allocated when actually written to. This distinction matters when testing “disk full” scenarios — a sparse file won’t actually fill the disk.

Q47
What is Cgroups and Namespace in Linux?
Intermediate

Ans:

These are the two Linux kernel features that make containers (Docker, containerd, etc.) possible — neither is Docker-specific; they’re general kernel primitives Docker happens to build on:

Namespaces — isolate WHAT a process can see:

NamespaceIsolates
pidProcess IDs — a process can’t see or signal processes outside its namespace
netNetwork interfaces, routing tables, ports
mntFilesystem mount points
utsHostname and domain name
ipcInter-process communication (shared memory, semaphores)
userUser/group IDs — root inside the namespace can be unprivileged outside it
# See the namespaces a process belongs to
ls -la /proc/<pid>/ns/

# Create a new process in a new set of namespaces manually (what container runtimes do)
unshare --pid --net --mount --fork --mount-proc bash

Cgroups (Control Groups) — limit HOW MUCH a process can use:

# Cgroups v2: create a group and cap its resources
sudo mkdir /sys/fs/cgroup/mygroup
echo "500M" | sudo tee /sys/fs/cgroup/mygroup/memory.max
echo "50000 100000" | sudo tee /sys/fs/cgroup/mygroup/cpu.max   # 50% of one CPU

# Add a process to the cgroup
echo <pid> | sudo tee /sys/fs/cgroup/mygroup/cgroup.procs

In one sentence: namespaces answer “what can this process see?” (isolation), cgroups answer “how much can this process use?” (resource limits) — together they’re the foundation every container runtime is built on, well before Docker existed as a project.

Q48
What is the difference between fork() and execve()?
Advanced

Ans:

These are two different, complementary system calls — most process creation in Unix/Linux is actually fork() immediately followed by exec():

Aspectfork()execve() (exec family)
What it doesCreates a new process — a near-exact copy of the calling processReplaces the current process’s program with a new one
ResultTwo processes now running the same code (parent + child)Same PID, but now running entirely different code
MemoryChild gets a copy-on-write copy of parent’s memoryOld memory image is discarded, replaced with the new program’s
Return valueReturns twice — 0 in the child, child’s PID in the parentDoes not return on success (the calling program no longer exists)
pid_t pid = fork();
if (pid == 0) {
    // Child process — pid == 0 here
    execve("/bin/ls", args, envp);   // child's memory is replaced with `ls`
    // Code after execve() only runs if execve() itself FAILED
} else if (pid > 0) {
    // Parent process — pid is the child's PID here
    wait(NULL);   // wait for child to finish
} else {
    // fork() failed (e.g., out of memory / process limit reached)
}

Why shells use both together: when you run ls in bash, the shell calls fork() to create a child process (so the shell itself keeps running), then that child calls exec() to become the ls program. This is also exactly why a fork() can fail with “Cannot allocate memory” even when RAM looks free — Linux’s overcommit accounting has to reserve enough virtual memory for a full copy of the parent before the fork can succeed, even though copy-on-write means most of it is never actually duplicated.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form