Search code examples
tclexpect

how to get the parent process id in expect script?


I want to know the parent processs id of the parent inside expect script how would i do it.

I used tried to use and got this error

[sesiv@itseelm-lx4151 ~]$ invalid command name "id"
    while executing
"id process parent "
    invoked from within
"set parent_process_id [ id process parent ]"

also tried to do

 puts "parent is ---$env(PPID)**"

but it gave me this

[sesiv@itseelm-lx4151 ~]$ can't read "env(PPID)": no such variable
    while executing
"puts "parent is ---$env(PPID)**""

Solution

  • The id command is part of the Tclx package, you need to include it:

    package require Tclx
    

    Update

    Since your system does not have the Tclx package, and based on your prompt, I guess you are running a Unix-like operating system, I am going to offer a solution which employs the ps command. This solution will not work under Windows.

    # Returns the parent PID for a process ID (PID)
    # If the PID is invalid, return 0
    proc getParentPid {{myPid ""}} {
        if {$myPid == ""} { set myPid [pid] }
        set ps_output [exec ps -o pid,ppid $myPid]
    
        # To parse ps output, note that the output looks like this:
        #   PID  PPID
        #   4584   613
        # index 0="PID", 1="PPID", 2=myPid, 3=parent pid
        set checkPid  [lindex $ps_output 2]
        set parentPid [lindex $ps_output 3]
    
        if {$checkPid == $myPid} {
            return $parentPid
        } else {
            return 0
        }
    }
    
    # Test it out    
    set myPid [pid]
    set parentPid [getParentPid]
    
    puts "My PID: $myPid"
    puts "Parent PID: $parentPid"