Inside a bash script, how to get PID from a program executed when using the eval command?

I have commands in a bash script that are similar to this:

eval "( java -classpath ./ $classname ${arguments[@]} $redirection_options $file )" &
pid=$!

However if I do a ps $pid it shows the main script process instead of the process of the java program.

It obtains the correct process when I omit the eval, but in order to get some of the complicated arguments to work correctly I need to use it.

Any idea of how I can get the PID of the java program when it's executed within an eval command?

Answers


Your ampersand is backgrounding the eval line, causing the (top-level) shell to fork a child, the child shell to eval the string and in turn run your java program as a grandchild of the top-level shell. So, $! reports the pid of the child shell, which is the most recently backgrounded command.

Instead move the backgrounding inside your eval:

eval "(java ...) &"
pid=$!

As long as the parenthetical doesn't get complicated enough to become a subshell, the above will work.


Need Your Help

Hibernate EntityManager persist() and database round trip count

database spring hibernate jpa hibernate-entitymanager

Right now I am using entitymanager to insert list of object entity to database with my dao using code like this.

How to pass a value from one view to another? (iPhone)

iphone objective-c

for example, I have a textfield, that records the user name, after I click the button, it will display the next view, and I want the next view ge the text field data, and display on the second view...