Redirecting standard output to a file containing the pid of the logging process

I searched for a while, but I can’t find an answer or come up with my own solution, so I am contacting you guys. The first question I ask here is :)

I would like to run several instances of the same program and redirect the standard output of each of these programs to a file containing the same pid process, something like:

my_program > <pid of the instance of my_program that is called in this command>.log

I know this doesn't even come close to the path: P I messed around with exec and $ PPID, but to no avail. My bash-fu is weak: | help me, call me somewhere! Thank!

+3
source share
2 answers

, , bash, PID, . , PID .

, bash exec.

. -, C, 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 script, PID , exec:

#!/bin/bash
# printpid.sh

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

a script, printpid.sh script :

#!/bin/bash
# example.sh

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

, :

$ 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, script - , bash , exec.

!

+3

bash 3 , , exec ${BASHPID}

, (), < pid > .log exec my_program, , pid ( ).

( exec my_program >${BASHPID}.log )

+2

Source: https://habr.com/ru/post/1767858/


All Articles