[Tutor] exec* and co.

D-Man dsh8290@rit.edu
Sat, 24 Feb 2001 16:11:34 -0500


On Sat, Feb 24, 2001 at 08:56:18AM +0000, Viktor Lakics wrote:
| I recently wrote a little python script to run fetchmail at certain
| times (depending on whether it is a weekday or weekend and certain
| times on a day). I have the script working, except the very last
| bit, to invoke fetchmail. Here is what I want with pseudo-code:
| 
| if weekDay() and workHours():
| 	run "fetchmail -d 2000"
| else:
| 	sys.exit

Just a note, you probably mean to call exit, so you need parenthesis.

sys.exit()


| 
| I did RTFM and know that I need to use one of the
| os.exec...commands. But I am confused about the syntax:
| 
| 1."os.execv('/bin/echo', ['foo', 'bar']" works, prints out only
| "bar". Foo is ignored. But "os.execv('ls', ['foo', '-al']" does not
| work, gives me an error. Why? What would be the syntax of "ls -al"?
| Also I am confused why we need execv execl execlp etc.? 
| 


The exec* family of functions descend directly from their C
counterparts.  I haven't used them, but I RTFM'd Linux Programming
(from Sams publishing).  The purpose of them is to replace the current
running process with a different one.  The various forms allow you
different ways of controlling the environment the replacement process
runs in.  (Very important when considering security)  Note that once
the exec call is complete, no more code from you program will run --
your process has been replaced by the new process.  It is usually
wrapped in an if-else with an associated fork() call.  The fork
duplicates the process.  Ex: (psuedo C/Pytnon)

pid = fork()
if ( pid == 0 ) :
    # this is the child process, replace with fechmail
    execv( "fetchmail" , other_args ) # I don't know the proper usage ;-)
else :
    # this is the parent (original) process, wait for the child to
    # exit
    exit_code = wait( pid )


This idiom is so common that both C and Python provide a convenience
function to do this for you.  However, if you are concerned with
security, don't use it. 


import os
exit_code = os.system( "fetchmail options and args as a string like in
bash" )


exit_code will be an integer, and is returned from main() (C programs)
or the argument to sys.exit().  (0 by default, means no errors)

HTH,
-D