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 -...")
 
 
(One intermediate revision by the same user not shown)
Line 15: Line 15:


# assign/create FD '5' to a file, what we can refere as a strem to read or write in the future
# 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
exec 5<>$FILE  # open a file for read and write (aka open a file handle)
# >  open for write
# >  open for write
# <  open for read
# <  open for read
# <> 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 '<'
Line 28: Line 28:
echo "File was read on: $(date)" >&5
echo "File was read on: $(date)" >&5


# Close FD, otherwise will stay open forever
# Close FD, otherwise will stay open forever (aka close file handle)
exec 5>&-
exec 5>&-
</source>
</source>

Latest revision as of 18:00, 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 (aka open a file handle)
# >  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 (aka close file handle)
exec 5>&-


File to read

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