简体   繁体   English

在bash脚本中获取commanad的子进程

[英]get sub process of commanad inside bash script

i'm trying to write a script to get the name and the pid of the process lanched from bash script. 我正在尝试编写一个脚本,以从bash脚本获取该进程的名称和pid。

example: 例:

#!/bin/bash
pass=(`command1 | grep .... | tail ... `)&
if [ "$?" = "0" ]; then
    echo "pid of the sub-shell "$!
    echo "pid of the shell "$$       
else
    echo $?
    exit 1
fi

the output of this script is 该脚本的输出是

pid of the sub-process 22725
pid of the shell 22724

My question is how can i get the the pid and the command of command1 from shell script, and the result of the command in pass variable. 我的问题是如何从shell脚本中获取pid和command1的命令以及pass变量中命令的结果。

  1. if i remove the "&" i get the result of the command ( password) but not the pid of sub-shell 如果我删除“&”,我将得到命令的结果(密码),但没有子shell的pid
  2. if i set the "&" i get the pid but not the password 如果我设置“&”,我会得到pid而不是密码

A bit more context would be helpful, for example, why do you need the subshell to output the name of command1, when you must write "command1" to execute it in the subshell in the first place? 多一点上下文会有所帮助,例如,为什么当您必须首先在子shell中编写“ command1”来执行它时,为什么需要子shell输出command1的名称?

If the requirement is just to get the subshell process ID along with its result, output them on separate lines: 如果仅是为了获取子shell进程ID及其结果,请在单独的行中输出它们:

{ read pid; read result; } < <(echo $$; echo mypass)

However the question suggests you want to launch the child process (which may be long-running), perform other activities, then get its output. 但是,该问题建议您要启动子进程(可能需要长时间运行),执行其他活动,然后获取其输出。 For this try named pipes (examples here ) or a temporary file: 为此,请尝试命名管道( 此处为示例)或一个临时文件:

temp=$(mktemp)
command1 ... >$temp &
pid=$!
# other activities here
# ...
wait $pid
read result <$temp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM