2

Let's say I have a file named file.txt and a running process with PID 12345 which sometimes reads and sometimes writes to that file.

  1. Is there any way I can fool the process with PID 12345 to read or write to memory (allocated by another process) every time it tries to read or write to file.txt?

  2. Is there any way I can fool the process to read and write to a different file (like file2.txt)?

Same question for Windows.

1
  • 4
    I think you can archive what you want using gdb (changing file descriptors on fly comes into mind) .
    – sebasth
    Aug 9, 2017 at 18:56

2 Answers 2

1
  1. You can create an unix domain socket named file.txt
  2. You can LD_PRELOAD a library that implements open() syscall so it will open the correct file, or in Linux you can use mount namespace with unshare and mount --bind in some cases.

Either way you can also LD_PRELOAD a library with read() and write() calls, but note that this won't work with statically linked executables; you will need to use ptrace if you need to handle these.

0

You cannot easily change what file you are reading from but you can easily change what file the file is you are reading from...

> cat file1
123456

> cat file2
abcdef

!/bin/bash
exec 4<>file1
read -n 1 -u 4 input
echo $input
read -n 1 -u 4 input
echo $input
read -n 1 -u 4 input
echo $input
read -p "Press enter to continue" cont
read -n 1 -u 4 input
echo $input
read -n 1 -u 4 input
echo $input
read -n 1 -u 4 input
echo $input

./testscript.sh
1
2
3
Press enter to continue
d
e
f

This is the result when you do cp file2 file1 while the script is waiting for your input. After copying the desired data into the file you may rename it but within the file system only.

Your running process is not going to pause like that so you have to pause it and restart it after the copying (and renaming) has finished with

kill -STOP 12345
kill -CONT 12345

You can copy a larger file into a smaller one but copying a smaller one into a larger one may cause unpleasant effects depending on the current position of the file descriptor within the file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .