Operating System - HP-UX
1838582 Members
3227 Online
110128 Solutions
New Discussion

Re: rename() doesn't fail

 
Vimala L
Occasional Advisor

rename() doesn't fail


Hello there.

I expect rename to fail in the following scenario.

===C program====
main ()
{
printf ("rename returns %d\n",
rename ("a", "b"));
}
let us say the compiled output a.out is available
======================

$ touch a
$ ln a b
$ mv a b <== This fails and echo $? gives 1
$ ./a.out <== The output is "rename returns 0"
Both the files are availble as it is but rename() in a.out is expected to return -1 as per the man page. Why is this not happening? How does "mv" command identifies this problem and exits with 1? Any sure way to rename "a" to "b" irrespective of what "b" is, using a C program?

Thank you,
Vimala
04-Mar-2003
5 REPLIES 5
Rajeev  Shukla
Honored Contributor

Re: rename() doesn't fail

Hi rename doesn't fail beacuse it moves the file a low level. i.e irespective of whether the file is there or not. That is the reason why it returns 0. To make that happen i.e rename() return 1 you'll have to check the file exsistance and compare if they are same then exit(1)

Vimala L
Occasional Advisor

Re: rename() doesn't fail


Thank you for your response.

If "rename" moves the file at low level, why is it still existing? Please help me to understand.

Thanks,
Vimala
Rajeev  Shukla
Honored Contributor

Re: rename() doesn't fail

rename() is a system call which is used for making mv command.
So rename is there for making your own programs. So before you use rename(), do the tests on file..
James A. Donovan
Honored Contributor

Re: rename() doesn't fail

I dont the following for a fact, but it seems reasonable to me....

mv fails in this case because "b" is a hard-link of "a". That is, all you've done with the ln command is to duplicate the directory table entry. A and B have the same inode. You can see this if you use "ll -i".

So the mv fails because you are essentially trying to replace a file with itself.

I think the rename succeeds because it acts on the directory tbale entries and not on the file itself.
Remember, wherever you go, there you are...
Adam J Markiewicz
Trusted Contributor

Re: rename() doesn't fail

Hi

The answer is quite easy in this case I think.

Why mv fails in this case? Because it checks this situation.
On my system I have:

$ touch a
$ ln a b
$ mv a b
mv: a and b are identical

hovever

$ touch a
$ touch b
$ mv a b

works.

Remember that mv is somewhat more than just a rename() call, because you can mv your files accross the filesystems (and this means real copying then).

Good luck

Adam
I do everything perfectly, except from my mistakes