r/ProgrammerTIL • • Sep 14 '21

Other Language [Unix] TIL root can write to any process' stdout

Start a long running process:

tail -f

In another shell:

# Get the process' ID (Assuming you only have one tail running)
TAIL_PID=$(pgrep tail)
# Send data to it
echo 'hi' > /proc/$TAIL_PID/fd/1

Observe the first shell outputs "hi" O.O Can also write to stderr. Maybe stdin?

121 Upvotes

14 comments sorted by

View all comments

21

u/HugoNikanor Sep 14 '21

It's not limited to root. Also, it's just that a process gets its controlling terminal as STDOUT (and STDERR and STDIN). For example:

$ ls -l /proc/1075623/fd/1
lrwx------ 1 hugo hugo 64 14 sep 16.51 /proc/1075623/fd/1 -> /dev/pts/1

5

u/ironykarl Sep 14 '21

Also, it's just that a process gets its controlling terminal as STDOUT (and STDERR and STDIN)

Can you explain this part? I wasn't sure what you meant.

4

u/HugoNikanor Sep 15 '21

When you start a program it gets the current terminal (which you can find by running tty) on all three standard ports

$ ls -l /proc/self/fd/{0,1,2}
lrwx------ 1 hugo hugo 64 15 sep 08.14 /proc/self/fd/0 -> /dev/pts/1
lrwx------ 1 hugo hugo 64 15 sep 08.14 /proc/self/fd/1 -> /dev/pts/1
lrwx------ 1 hugo hugo 64 15 sep 08.14 /proc/self/fd/2 -> /dev/pts/1

(Notice how it's /dev/pts/1 for all three.)

1

u/emmelaich Oct 11 '21

Check the manual page for mesg

1

u/HugoNikanor Oct 19 '21

Didn't know that there was a dedicated command for turning off that feature! Though it mostly seems to do chmod [+-]w $(tty). Also, while it's a nifty idea to chat by writing to each others terminals, it not only falls flat on a pure annoyance factor, but in $CURRENT_YEAR it also fails due to everyone having a myriad of active terminals, along with way to many curses (and similar) programs running.