Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

BASH detaching from tty when run in background with '&'

Status
Not open for further replies.

akaKul

Programmer
Jan 3, 2003
3
GB
Hi
I have a bash script that I need to run both interactivly and non-interactivly (ie via crond or using '&').
This script echo's my lovely junk to the terminal if run interactivly, or to a file if run via crond.
I use: (Which works fine!!)
if [ -z $(tty) ]; then
exec > the_file 2>&1
fi

However I need the bash script to also be able to completly detach from the tty/pts session when run in the background ... ie ./script.sh & Which currently it is still aware that it has a terminal attaxched and displays the results to the tty/pts terminal :(

Any ideas how i can convince the script it is NOT running interactivly when it is run using '&' ?

Many Thanks
Kul
 
Hi,
How about passing a parameter to the script:
script.sh bg
----------------------------
case "$1"
bg) ..background commands
*) ..anything else - foreground commands
esac
 
Hiyas,

Ok the parameter thing will undoubtly work, but is a little cumbersome and eextreemly likely i will forget to use it :(

Using 'nohup' doesnt unfortunatly detach the job from the issuing terminal fully, the session is inherrited and means that the 'tty' type woudl aalso be inherrited :(

So....
After searching for the whole day on the net with every conceivable combination of search patterns, I have concluded there is nothing about this, and bash doesn't have this facility built in :(

So now my BASH does(will)....
Here is 'a' solution, and VERY workable, providing exactly what I need:

file blah.c
#include <termios.h>
#include <stdlib.h>
int main( void ) {
struct termios term;
tcgetattr(2, &term);
if (!(term.c_lflag & ECHO))
exit(0);
exit(1);
}

gcc blah.c -o blah
chmod 700 blah

in my script....
./blah
if [ $? -eq 0 ]; then
exec > the_file 2>&1
fi

(in addition/combination to the original mail!)


Now we can tell if there is a terminal attached to the job, even when executed using the 'nohup' and/or '&', or even if run from 'at', 'batch' or 'crond'. :) Regards, Kul
Need Very FAST Dial-Up Access:
 
Hey Kul,

I had a similar issue where my proc would die when I exited. My final solution was to start a second session and kill -9 the first shell. So in steps:

1)nohup script.sh &
2)Start new session
3)ps -u <username> (note the shell start time)
4)kill -9 <pid> (where pid is the first shell poc number)

I know it's messy but it worked for me! ...and oddly enough, I don't always have to do this... :)

Good luck!
-pd
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top