Question

Read some where that one should use WEXITSTATUS to check for return status of system calls . However I dont think that a call like system("mv /a/b/c /a/b/d") needs a check if it fails .

What are the conditions when this call may fail ?

Was it helpful?

Solution

Some possibilities:

  1. /a/b/c does not exist
  2. /a/b does not exist
  3. You have insufficient access to /a/b/c
  4. You have insufficient access to /a/b/d
  5. /a/b/d already exists
  6. /a/b/c isn't moveable
  7. There is no shell
  8. mv does not exist
  9. You have insufficient access to mv
  10. You have no file system mounted
  11. You have no storage available at all

And many, many more...

OTHER TIPS

system("mv /a/b/c /a/b/d") : very probably both /a/b/c and /a/b/d lie on the same mounted file system. I am guessing you have a Posix system, perhaps Linux.

Then it is much more simpler to use the rename(2) syscall (which is called by /bin/mv when relevant!) and directly code:

if (rename("/a/b/c", "/a/b/d")) {
   perror("rename failed");
   exit(EXIT_FAILURE);
}

and you would have thru errno(3) i.e. thru perror(3) the error code explaining why the rename failed. All the error conditions in rename(2) are relevant failure cases of mv, see also mv(1)!

Read Advanced Linux Programming.

If (for some strange reason, e.g. bind mounts, symlinks, ...) /a/b/c and /a/b/d don't lie in the same filesystem, you would get errno == EXDEV (and you might handle that case by a copy followed by an unlink of the source).

In general, using system("mv ...") should be avoided. See this answer and this one explaining why (and also this and this). And your user may have a different mv in his PATH (or some alias), so mv should at least be /bin/mv ... If . (or even worse /tmp !) is early in his PATH and has a symlink mv/bin/rm your user won't be happy!

BTW, you generally don't call system with a compile-time constant string starting with mv. That string is generally built. And if you don't quote correctly things (imagine one argument being ; rm -rf $HOME) havoc can happen. Also, system(3) can fail e.g. because fork(2) failed (too many user processes, reaching the RLIMIT_NPROC limit of setrlimit(2)...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top