-1

I'm trying to understand how cp command is similar to/different from a read/write combination in terms of context switches. In other words, is using cp to copy data from within application equivalent to using read/write combination. I think read/write combination does 4 context swiches - user context - kernel context (data copied to kernel buffer, then data copied to user space) - user context, for reading, and then another set of 2 context switches for write. How many context switches would happen for cp? Also would zero-copy or sendfile be better than using cp?

I'm on linux platform and using kernel later than 2.4.

Thanks.

user900563
  • 237
  • 2
  • 3
  • 10

3 Answers3

1

I've checked the source code for cp from fileutils 4.1, and it copies regular files by calling read() and write() in a loop. So for that particular cp, there's no difference between it and a read/write loop.

Now, the number of calls to read() and write() clearly depend on the size of the buffer used for copying.

Finally, it is hard to see how the number of context switches is even relevant, given that the copy is almost certainly going to be I/O-bound. If it is relevant in your particular circumstances, you might want to elaborate on what they are so that we can address those circumstances.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Context switches are expensive. I know how many of them are involved in a read/write combination to transfer a file. But wanted to know if using cp is same. So the user is tranferred 4 times before it finally reaches the destination. Which essentially means that using sendfile should be faster than cp. Right? – user900563 Dec 10 '11 at 14:19
0

Context switches also happen asynchronously. In particular, for every system clock tick (which happen every 20 or even 1 millisecond) - because then the kernel reschedule running tasks.

I think you should not care that much about them inside a cp process.

You could care about reducing the number of system calls; for a file copy, that means larger buffers when calling read & write

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

Take a look at splice:

Community
  • 1
  • 1
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526