Difference between revisions of "Linux File Descriptors"

From Ever changing code
Jump to navigation Jump to search
(Created page with "It's an index table from 0..n per process that indicates what files,pipes,sockets the process has open. File Descriptors 0,1,2 are reserved for OS, for: * 0 - STDOUT * 1 -...")
 
Line 20: Line 20:
# <> open for rw
# <> open for rw


while read -r CITY; do
while read -r CITY; do # read a file line-by-line
   echo "City name: $CITY"
   echo "City name: $CITY"
done <&5 # instead redirecting a file value, we redirect a FD for reading '<'
done <&5 # instead redirecting a file value, we redirect a FD for reading '<'

Revision as of 17:59, 6 November 2019

It's an index table from 0..n per process that indicates what files,pipes,sockets the process has open.


File Descriptors 0,1,2 are reserved for OS, for:

  • 0 - STDOUT
  • 1 - STDIN
  • 2 - STDERR


Following script demonstrates FD usage:

#!/bin/bash
echo "File name to read: "
read FILE  # type 'cities.txt', this file must exist

# assign/create FD '5' to a file, what we can refere as a strem to read or write in the future
exec 5<>$FILE   # open a file for read and write
# >  open for write
# <  open for read
# <> open for rw

while read -r CITY; do # read a file line-by-line
  echo "City name: $CITY"
done <&5 # instead redirecting a file value, we redirect a FD for reading '<'
# &<number> - ampersand indicates that it's FD

# Write to a file but instead using a file we use FD for writting '>'
echo "File was read on: $(date)" >&5

# Close FD, otherwise will stay open forever
exec 5>&-


File to read

cat > cities.txt << EOF
Osaka
Warsaw
London
EOF