0

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.

3
  • 1
    The process has already terminated; it takes much less than one second to copy a file with a single short line. Commented Nov 22, 2023 at 10:08
  • If this is just for experimentation, make the script do something which blocks it, like an endless loop, or reading from an empty FIFO. Commented Nov 22, 2023 at 10:09
  • Even if you would get rid of the race conditions: What makes you think, that your background process actually is using FD 3? Commented Nov 22, 2023 at 14:03

1 Answer 1

0

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.