How to read an open file through a file descriptor from proc?

218 Views Asked by At

I'm trying to learn how to work with proc and file descriptors. I want to start a process that opens a file, read the same file in parallel through a file descriptor from proc.

I tried to do this:

#!/bin/bash
echo "Hello, world!" > script.txt
cat script.txt &
pid=$!
sleep 1
cat "/proc/$pid/fd/3"
kill $pid

I got this result:

Hello, world! cat: /proc/5087/fd/3: No such file or directory ./script.txt: line 13: kill: (5087) - No such process

Perhaps the problem lies in opening the file using cat, but I do not know what it can be replaced with so that the file is opened before the attempt to read through the file descriptor. Please tell me how to fix this.

1

There are 1 best solutions below

0
xpusostomos On

You need a command that won't instantly slurp it all up, and close the fd before you can do your playing. The shell read command comes to mind, however it reads from stdin, so you won't find the result on fd 3, but on fd 0:

#!bin/bash
echo "Hello
to
the
world!" >script.x
( read A; sleep 10) <script.x &
pid=$!
cat /proc/$pid/fd/0
kill $pid

If you need to play with fd 3, you'll have to think of a command that can open a file, but not immediately consume it all. Certainly you could write one in C very easily. Just call open('script.txt', ....) and then sleep(100);