Shell – How to use / send signals at the command-line, for any program (eg. dd)

background-processshellsignals

I trying to understand the manpage of the dd program, which mentions:

Sending a USR1 signal to a running 'dd' process makes it print I/O statistics to standard error and then resume copying.

         $ dd if=/dev/zero of=/dev/null& pid=$!
         $ kill -USR1 $pid; sleep 1; kill $pid

What does pid=$! mean?

Is this an assignment of a variable, which gets the pid of dd?
And is eventually used in the $pid variable?

Also why do they use sleep and kill?

Is this the way to use -USR1?

Best Answer

dd if=/dev/zero of=/dev/null&

The trailing & means run the prefix command in background. (Disclaimer: This is oversimplified statement)

Refer to this:

$! is the PID of the most recent background command.

So pid=$! assign the most Recent background PID to variable pid, which is dd PID.

Also why they use sleep and kill?.

You need kill $pid (if not specified parameter, default signal for kill is TERM which is process termination) to terminate the dd process after you done testing, otherwise dd process may just stay in background and exhausting your CPU resources. Check your System Monitor of your platform to see.

Whereas Kill -USR1 $pid print I/O statistics, it doesn't terminate the process.

Without sleep 1 second, your dd process may get terminated by last command statement kill $pid** before have the chance to write statistics output to your terminal. The processes is synchronous but trap+write operation (kill -USR1 $pid) may slower than terminate operation (kill $pid). So sleep 1 second to delay the startup of kill $pid to ensure statistics output done printing.

This is the way to use -USR1?

Just man dd:

Sending a USR1 signal to a running 'dd' process makes it print I/O statistics to standard error and then resume copying.

And man 7 signal:

   SIGUSR1   30,10,16    Term    User-defined signal 1
   SIGUSR2   31,12,17    Term    User-defined signal 2

Combine both statements , you should understand USR1 is User-defined signal which is defined by dd to provide a way for user to interrupt it and print I/O statistics on the fly. It's program specific handler, it doesn't means you can kill -USR1 other_program_pid and expect statistics output.

Also you might interest about this: Why does SIGUSR1 cause process to be terminated?.