如何在expect脚本中获取父进程id?

时间:2013-04-24 13:05:33

标签: tcl expect

我想知道父进程在期望脚本中的父进程id我该怎么做。

我曾经尝试使用并得到此错误

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

也尝试过做

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

但它给了我这个

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

1 个答案:

答案 0 :(得分:3)

id命令是Tclx包的一部分,您需要包含它:

package require Tclx

更新

由于您的系统没有Tclx软件包,并且根据您的提示,我猜您正在运行类Unix操作系统,我将提供一个使用ps命令的解决方案。此解决方案在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"