What happens when I kill 'cp'? Is it safe and does it have any consequences?
This is safe to do, but naturally you may not have finished the copy.
When the cp
command is run, it makes syscalls that instruct the kernel to make copies of the file. A syscall is a function that an application can call that requests a service from the kernel, such as reading or writing data to the disk. The userspace process simply waits for the syscall to finish. If you were to trace the calls from cp ~/hello.txt /mnt
, it would look something like:
open("/home/user/hello.txt", O_RDONLY) = 3
open("/mnt/hello.txt", O_CREAT|O_WRONLY, 0644) = 4
read(3, "Hello, world!\n", 131072) = 14
write(4, "Hello, world!\n", 14) = 14
close(3) = 0
close(4) = 0
This repeats for each file that is to be copied. No corruption will occur because of the way these syscalls work. When syscalls like these are entered, the fatal signal will only take effect after the syscall has finished, not while it is running. Because of this, forcibly killing the process will only cause it to terminate after the currently running syscall has finished. This means that the kernel, where the filesystem driver lives, is free to finish the operations that it needs to complete to put the filesystem into a sane state. Any I/O of this kind will never be terminated in the middle of operation, making them atomic operations.
Interestingly, this is why commands like cp
may not terminate immediately when they are killed. If you are copying a very large file and kill it, even with SIGKILL, the process will still run until the current syscall finishes. With a large file, this may take a while, as the process will be in an uninterruptible state.
Since cp
is a userspace command, this does not affect filesystem integrity.
You of course need to be prepared that at least one file will not have been copied completely if you kill a runnning cp
program.