Redirecting stdout and stderr from a background process

I have a script called foo that runs the a.exe program and sends the time statistics to a file, time.log

#!/bin/bash date 1>> time.log (time ./a.exe) 2>> time.log 

This works if I run the script in the background of my terminal and leave my shell open until a.exe finishes working, but if I run the script in the background and exit my terminal (a.exe takes a long time to run )

 foo & exit 

when I get back, I executed a.exe, but the time statistics are not displayed in my log file. Does anyone know why this is? Is there a way to get time statistics after I closed the parent shell?

thanks

+4
source share
5 answers
 nohup foo & 

When you exit the shell, it sends a SIGHUP signal to all the child processes that kill them by default. If you want the process to continue to run even when the parent shell is complete, you will need to ignore SIGHUP.

NAME

nohup - invoke a freeze-protected command

SYNTAX

 nohup utility [arg ...] 

DESCRIPTION

The nohup utility invokes the command with its arguments and at the same time sets ignoring the SIGHUP signal. If standard output is a terminal, standard output is added to the nohup.out file in the current directory. If the standard error is a terminal, it is directed to the same place as the standard output.

+5
source

Since the question is marked as bash , I quote from man bash

 disown [-ar] [-h] [jobspec ...] Without options, each jobspec is removed from the table of active jobs. If jobspec is not present, and neither -a nor -r is supplied, the shell notion of the current job is used. If the -h option is given, each jobspec is not removed from the ta‐ ble, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a job‐ spec does not specify a valid job. 

This is useful when you get started, but you forgot the prefix with nohup . Just do

 disown -ah disown -a 
+2
source

Try:

 nohup <your_command> & 
0
source

Remember to remove all links to tty / pts, 0 </ dev / null removes the stdin link.

0
source

Your a.exe will be killed when you close the parent shell.

You can dial the screen, run the command as usual, and exit the screen. This prevents the process from being killed when the parent shell exits. This method is a bit cumbersome, but can be convenient in other situations.

John gave a much better answer - use nohup.

0
source

All Articles