Перейти к содержимому

как передать вывод grep в "lsof -p"

1

Я хочу знать путь в настоящее время работает ./a.out

Есть несколько процессов MPI, но мне нужен только один из PID из нескольких ./a.out. Поэтому я сначала использую код ниже, чтобы grep это

ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1 

который дает один пид, например, 12345

Теперь я хочу использовать

lsof -p12345 

знать путь к файлу PID 12345

Как объединить два шага в одну командную строку?

1 252 просмотра
user15964 спросил 10 лет назад
U 126

3 ответа

3
Принятый ответ

This is the command that you need:

ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1 | xargs lsof -p 

The key here is xargs.

Commands such as grep and awk can accept the standard input (STDIN) as a parameter, or argument by using a pipe. However, others such as cp, echo and lsof disregard the standard input stream and rely solely on the arguments found after the command.

Using the command xargs you can build and execute command lines from standard input.

jcbermu ответил 10 лет назад
J 15 506
1

I would recommend using xargs when a command returns multiple lines (or records). In this case, the command returns a single PID and a shell feature known as command substitution would be an appropriate solution.

This allows the output of one command to be used by another and is accomplished by wrapping the command that provides the input in $( and ). In the past, backticks (`) were used but these are no longer recommended.

lsof -p $(ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1) 

Я только что узнал $ () вчера, но забыл использовать его здесь .... Большое спасибо

user15964 · 10 лет назад · 1
Anthony Geoghegan ответил 10 лет назад
A 2 738
1

Your 1st complex command to find the PID based on name can be replaced by pgrep, e.g.

$ pgrep -nf a.out 70512 

Then to get the path from lsof, you can use conditional print in awk.

So the command could be:

$ lsof -p $(pgrep -nf a.out) | awk '$4 == "cwd" ' 

Above is based on the following lsof output:

$ lsof -p $(pgrep -nf a.out) COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME gsleep 70513 kenorb cwd DIR 1,4 1938 121793972 /my/path 

Мне очень нравится ваш ответ. pgrep в сочетании с awk очень удобен для такого рода задач. большое спасибо

user15964 · 10 лет назад · 1
kenorb ответил 10 лет назад
K 10 504