Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

linux - how can I find who call my bash application

This may look a silly simple question, but I can't find the appropriate method to find the caller.

I have a tool that can be used from different applications. I want to record who is using it.

Note that when sourcing, using source (or the dot shortcut), the executing program is bash (or your designated shell). In this case, only if you source 'tool', the calling history will be preserved on ${BASH_SOURCE[*]}, including the calling line on ${BASH_LINENO[*]}.

I expect BASH_SOURCE give some hint (history), however, the tool is not sourced so, there is no references to caller on 'BASH_SOURCE'.

#!/bin/bash
# this is the tool: I'm expecting to have 'client' somewhere
echo "Source ${BASH_SOURCE[*]}"
ps -axj | grep "s$$s"
echo "tool: ${*}"

now, this is the client caller

#!/bin/bash
# this is the client
chmod +x ./tool            # I'm making this explicit
./tool this is a test

This is the result:

$ . ./client
Source ./tool
30389 17217 17217 30389 pts/1    17217 S+       0   0:00 /bin/bash ./tool this is a test
17217 17218 17217 30389 pts/1    17217 R+       0   0:00 ps -axj
17217 17219 17217 30389 pts/1    17217 S+       0   0:00 grep s17217s
30380 30389 30389 30389 pts/1    17217 Ss       0   0:01 -bash
tool: this is a test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might help with Linux:

#!/bin/bash
GPPID=$(ps -o ppid= -p $PPID | tr -d ' ')
cat /proc/$GPPID/comm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...