0

I tried attaching to a running process with gdb to redirect its stdout to an external file with these commands:

#Attaching
gdb -p 123456

#Redirecting (within GDB)
(gdb) p dup2(open("/tmp/my_stdout", 1089, 0777), 1)

I used the number 1089 because it represents O_WRONLY | O_CREAT | O_APPEND.

Firts, GDB just complained about some missing return types:

'open64' has unknown return type; cast the call to its declared return type

So I modified my command to

#Redirecting (within GDB)
(gdb) p (int)dup2((int)open("/tmp/my_stdout", 1089, 0777), 1)

This was successfully executed, and also works.

I'm trying to figure out how can I write a small utility that does the exact same thing as the above:

  1. attaches to a process by PID
  2. calls this (int)dup2((int)open("/tmp/my_stdout", 1089, 0777), 1)

Part2 seems easy, however part1 doesn't seem to work on aarch64. I could manage to work it on arm though.

There are a quite a few solutions which tries to solve this problem:

  • reptyr (doesn't work on process started by systemctl)
  • reredirect (doesn't support aarch64 at all)
  • injcode (doesn't support 64bit at all)
  • neercs (for sure no support for aarch64)
  • retty (for sure no support for aarch64)

If GDB can work, this is surely possible, but GDB is huge to analyze, and I hope I have some better solution which would not take weeks or months, like digging myself into GDB's source.

Daniel
  • 2,318
  • 2
  • 22
  • 53
  • You didn't explain why GDB is not good for you. Can't it be installed? Does it take too much time to start? Please specify your pain and maybe GDB with the proper argument can still be your friend here. – Eytan Naim Jun 16 '22 at 14:38
  • GDB is too large for my needs, and it's also too heavy (I only need to call `dup2` occasionally, nothing else). – Daniel Jun 16 '22 at 15:17
  • It is not ideal for your use case but you might be able to use `peekfd` to sniff foreign process fds – Eytan Naim Jun 16 '22 at 19:44

0 Answers0