##############
# Exercise 2 #
##############

# The objective of this exercise is to learn that some programs take some 
# time to complete their job, which are the differences between running 
# them in background or foreground and how this running programs, also 
# called process, can be monitored, stopped and terminated.


# NOTE: everything inside two " % " must not be typed literally, its meaning must be typed.

# we start from our $HOME
cd

# we go to the previously created WORK directory
cd PRACT_SO/WORK/

# we try to execute clustal2_sleep, a multiple sequence alignment program
clustalw2_sleep -ALIGN -OUTFILE=Lex_A.all.aln -INFILE=LexA_all.fst
# clustalw2_sleep did not execute because our current directory is not in our path

#we check our path
pwd

#we check which directories are in PATH
echo $PATH

# we can execute clustalw2_sleep using an absolute PATH
# /home/$USER/PRACT_SO/WORK/clustalw2_sleep  -ALIGN -OUTFILE=Lex_A.all.aln -INFILE=LexA_all.fst
# but we execute it using a relative PATH which is easier (by now you should understand the "./" and why now clustalw_sleep works
./clustalw2_sleep -ALIGN -OUTFILE=Lex_A.all.aln -INFILE=LexA_all.fst
# we press "ENTER" and observe how the terminal seems dead
# we press "Ctrl z" and observe how we recover the terminal but we see this mesage "[1]+  Stopped"
# this means that our program has paused execution

# we execute "ps" in order to see which process are running in our shell and their "pid"
# pid = Process Identifier
# ppid = PARENT Process Identifier
ps -f

#compare clustalw2_sleep PPID with the bash PID. This bash is the parent of clustalw2_sleep. This bash is the program in execution that you are using to interact with the OS.

# we send our process to the background so the execution continues and we still can use the terminal
bg

# if the program ends here repeat: execute it again, "Ctrl z", bg, ps -f

# we try to see how many resources our program is using in real time
# to refresh "top" screen use space bar
top -p %clustal2_sleep pid%

# we execute the process in the background adding the "&" at the end
./clustalw2_sleep -ALIGN -OUTFILE=Lex_A.all.aln -INFILE=LexA_all.fst &
# press enter to see that you have recover the prompt

# we send it to the foreground
fg

# we kill it pressing Ctrl c

# we execute the process in the background again
./clustalw2_sleep -ALIGN -OUTFILE=Lex_A.all.aln -INFILE=LexA_all.fst &

# we execute ps to see its pid (observe that the pid is different)
ps -f

# we kill it using "kill"
kill %clustal2_sleep pid%

# we execute ps to see that clustal2_sleep is not there anymore
ps -f

# we return to our $HOME
cd
