将标准输出重定向到包含日志记录进程的pid的文件

将标准输出重定向到包含日志记录进程的pid的文件

问题描述:

我搜索了一段时间,但我不能找到一个答案或提出我自己的解决方案,所以我转向你们。第一个问题我实际上问这里:)

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 :)

我想运行同一个程序的几个实例,并重定向每个这些程序的标准输出到一个文件,包含相同的进程'pid,类似:

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

这甚至不是接近的方式去:PI已经修复与exec和$ PPID,但无济于事。我的bash-fu是弱:|请帮助我,指点我什么地方!感谢!

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!

这里的问题是每个由bash启动的新进程都会获得新的PID,过程开始之前。但是你不能知道什么PID将被操作系统分配给该进程。

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.

这个问题的解决方案不是启动一个新的进程,而是替换现有的bash进程一个新的使用 exec

The solution to this problem is not to start a new process, but replace the existing bash process with a new one using exec.

这是一个例子。首先,我们编写一个打印其PID的基本C程序:

Here is an example. First, we write a basic C program that prints its PID:

// printpid.c

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    printf ("C process pid is %d\n", getpid());
    return 0;
}

然后我们写一个简单的bash脚本,打印它的PID,此程式使用exec:

Then we write a simple bash script that will print its PID and replace itself with this program using exec:

#!/bin/bash
# printpid.sh

echo Bash process PID is $$
exec ./printpid > $$.log

现在,让我们编写一个脚本来调用 printpid .sh 脚本多次:

Now, let's write a script that will call this printpid.sh script multiple times:

#!/bin/bash
# example.sh

./printpid.sh
./printpid.sh
./printpid.sh

现在,让我们确保它的工作原理:

Now, let's make sure it works:

$ ls
example.sh  printpid  printpid.c  printpid.sh
$ ./example.sh 
Bash process PID is 6397
Bash process PID is 6398
Bash process PID is 6399
$ ls
6397.log  6398.log  6399.log  example.sh  printpid  printpid.c  printpid.sh
$ cat 6397.log 
C process pid is 6397
$ cat 6398.log 
C process pid is 6398
$ cat 6399.log 
C process pid is 6399
$ 

请注意,当您使用 exec 时,您无法在脚本中放置任何其他内容,因为bash shell会将其替换为为 exec 指定为命令行参数的新进程。

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 for exec.

好运气黑客!