将标准输出重定向到包含日志记录进程 pid 的文件
我已经搜索了一段时间,但找不到答案或提出自己的解决方案,所以我向你们求助。我实际上在这里问的第一个问题:)
我想运行同一程序的多个实例,并将每个程序的标准输出重定向到包含同一进程'pid的文件,例如:
my_program > <pid of the instance of my_program that is called in this command>.log
我知道这是甚至还没有结束:PI 已经对 exec 和 $PPID 进行了修改,但没有成功。我的 bash-fu 很弱:|请帮助我,给我指出一个地方!谢谢!
I've searched for a while but i can't either find an answer or come up with a solution of my own, so I turn to you guys. First question I actually ask here :)
I would like to run several instances of the same program, and redirect each of these programs' standard output to a file that contains that same process' pid, something like:
my_program > <pid of the instance of my_program that is called in this command>.log
I'm aware that this is not even close of the way to go :P I have tinkered around with exec and $PPID but to no avail. My bash-fu is weak :| please help me, point me somewhere! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题是 bash 启动的每个新进程都会获得新的 PID,并且您必须在启动该进程之前重定向该进程的输出。但你无法知道操作系统将给该进程分配什么 PID。
解决这个问题的方法不是启动一个新进程,而是使用 exec 将现有的 bash 进程替换为新进程。
这是一个例子。首先,我们编写一个打印其 PID 的基本 C 程序:
然后编写一个简单的 bash 脚本,该脚本将打印其 PID 并使用 exec 将其自身替换为该程序:
现在,让我们编写一个脚本来调用 printpid.sh多次 脚本:
现在,让我们确保它有效:
请注意,当您使用
exec
时,您不能在脚本中添加任何其他内容,因为 bash shell 会用新进程替换自身指定为 exec 的命令行参数。祝黑客好运!
The problem here is that each new process started by bash gets new PID and you have to redirect the output of that process before starting it. But you cannot tell what PID will be assigned to that process by OS.
The solution to this problem is not to start a new process, but replace the existing bash process with a new one using
exec
.Here is an example. First, we write a basic C program that prints its PID:
Then we write a simple bash script that will print its PID and replace itself with this program using exec:
Now, let's write a script that will call this
printpid.sh
script multiple times:Now, let's make sure it works:
Be aware that when you are using
exec
you cannot put anything else after that in the script as bash shell replaces itself with a new process specified as command line arguments forexec
.Good luck hacking!
如果您有 bash 3 或更新版本,您可以组合子 shell、exec 和 ${BASHPID}
即,使用 ( ) 创建一个子 shell,然后设置重定向到.log 并执行 my_program,这应该替换子shell的进程映像,继承它的pid(除其他外)。
<代码>
( 执行 my_program >${BASHPID}.log )
If you have bash 3 or newer, you could combine subshells, exec and ${BASHPID}
That is, create a subshell with ( ), then set up redirection to <pid of subshell>.log and exec my_program, which should replace the process-image of the subshell, inheriting it's pid (among other things).
( exec my_program >${BASHPID}.log )