TABLE OF CONTENTS


::pwtk::bg

SYNOPSIS

proc ::pwtk::bg {args} {

USAGE

   bg  ?-r?  ?-s?  ?-np?  ?-id ID?  ?-fid FID?  script ?script? ?script ...?

OPTIONS

REMARK

Options -s, -np, -fid, -id are typically only used internally by PWTK.

PURPOSE

Arranges for a script, formed by concatenating all the script arguments, to run in a background (technically, the script is executed by launching a new PWTK process in the background). Hence, the command returns immediately. To wait for the job to finish, use the ::pwtk::bg_wait command.

ARGUMENTS

The script to be executed in a background is formed by concatenating all the script arguments. For example, the following two examples are equivalent:

      ::pwtk::bg print "I am a new bg job"

      ::pwtk::bg {
          print "I am a new bg job"
      }

RETURN VALUE

SOURCE

    variable bg

    set id [incr bg(count)]
    set index  $id
    set findex $id
    set bg($id,redirect) 0
    
    set options {
        {r         "redirect the stdout of this bg job to a log file"}
        {s         "silent mode"}
        {np        "do not use the propagate mechanism (default = use propagate)"}
        {fid.arg {} "the File-ID used for assembling the filename of the script"}
        {id.arg  {} "the explicit ID number"}
    }
    set nargmin 1
    set nargmax -1
    set usage "?-r?  ?-id ID?  ?-fid FID?  script ?script? ?script ...?"
    ::pwtk::parseOpt_
    
    if { $opt(r) } {
        set bg($id,redirect) 1
    }
    if { $opt(id) ne {} } {
        set index $opt(id)
    }    
    if { $opt(fid) ne {} } {
        set findex $opt(fid)
    }    
    if { [llength $args] == 1 } {
        set args [concat {*}$args]
    }

    if { [set head [file tail [file rootname [info script]]]] ne {} } {
        append head .
    }

    set scr bg.${head}$findex.pwtk
    set log bg.${head}$findex.log

    if { !$opt(s) } {
        print BG "Background job No.$index" 
        print "Script to run for background job-$index:\n\n[string trim $args]\n"
    }
    print "Script to run for background job-$index written to: $scr"
    if { $bg($id,redirect) } {
        print "Output of background job-$index redirected to a log file:  $log"
        set bg($id,log) [open $log w]
    }
    puts ""
    
    if { $opt(np) } {
        writeFile $scr $::pwtk::pkg_init_script\n$args
    } else {
        writeFile $scr $::pwtk::pkg_init_script\n[::pwtk::propagate_dump]\n$args
    }

    set bg($id,chan) [open [list | tclsh $scr] r]
    fconfigure $bg($id,chan) -blocking 0 -buffering line
    fileevent  $bg($id,chan) readable [list ::pwtk::bg_fileevent_ $id]

    return $id
}