ban
ban

Reputation: 685

Get PID of a process as it opens

How do I get the pid of a process as soon as it opens. Like lets say we run ./file.pl and then ./file2.pl As both these files will create a pid in /proc/ folder. How do I instantly know if the process has been created when the executable is run. I have a file with all the commands ready to be run as soon as it gets the green signal that there is a new process in the /proc/ folder. How do I do that? EDIT: Please don't answer with a shell command. I don't need to know the pid. I need to develop a script which can know right away that we have a guest in the proc department

Upvotes: 0

Views: 744

Answers (4)

Prashanth Reddy
Prashanth Reddy

Reputation: 1

Try out below shell script.(You may have to include changes in below script for your expected output)

#!/bin/bash
nr_proc_before=`ls -l /proc | wc -l`
ls /proc > proc_list_before

./any_executable &

nr_proc_after=`ls -l /proc | wc -l`
ls /proc > proc_list_after
nr_new=`expr $nr_proc_after - $nr_proc_before`

echo "$nr_new processes are created newly"
echo "new processes pids are :"
diff proc_list_after proc_list_before > new_pids
sed "1d" new_pids

if [ nr_new > 0 ] ; then
   #trigger your file which has commands.
fi

Insted of any_execuatble you can replace with your things so that new processes will be created.

Note : This is not a script which monitors for new process. This sample of script may give you idea to solve your problem. Please do reply for this answer, i can redefine my answer.

Upvotes: 0

Every process can get its own pid with the getpid(2) syscall. At process creation by fork(2) the parent process (e.g. some shell) gets the pid of the new child process. Read e.g. Advanced Linux Programming for more. And the kernel (not the program) is creating some subdirectory /proc/1234/ see proc(5) as soon as it creates the process of pid 1234.

Actually, /proc/ is not a real file system. It is just a pseudo file system giving a view on the state of the kernel and the entire Linux system.

Perl gives you its POSIX module to interface the syscalls. The getpid() syscall is interfaced using the $PID or $$ Perl variable.

The /proc/ pseudo filesystem is filled by the kernel. You could perhaps use inotify to follow change in /proc/ but this is very probably a bad idea.

Your question is not clear, we cannot understand what you really want to do and what you have tried.

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185106

If the script give you the shell prompt back, you can do :

./your_prog
pidof -x your_prog

Tested OK with this perl script :

#!/usr/bin/perl

if (fork() == 0) {
    sleep(600);
}

you need to

chmod +x your_prog

before...

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157967

If you start the process via a shell, then start process in background:

./your_prog &

Get the pid:

echo $!

Upvotes: 1

Related Questions