简体   繁体   English

不能删除(rm)c程序中的文件,但可以在shell中

[英]cannot delete (rm) a file in c program but can in shell

My C program (on Linux) needs to delete a file, say, /home/me/myfile, here is how I do it in my program 我的C程序(在Linux上)需要删除一个文件,比如/ home / me / myfile,这是我在程序中的操作方式

...
system ("rm -f /home/me/myfile");
...

When running this program, I got a message saying permission denied. 运行此程序时,我收到一条消息,说明权限已被拒绝。 BTW, ls -al /home/me/myfile returns -rw-r--r-- BTW, ls -al /home/me/myfile返回-rw-r--r--

However, under the same user account and in the same shell I execute the C program, I can simple delete the file by typing rm -f /home/me/myfile 但是,在相同的用户帐户和同一个shell中我执行C程序,我可以通过输入rm -f /home/me/myfile来简单地删除文件

What did I miss here? 我在这里想念的是什么?

Thanks, 谢谢,

Update: Using remove(/home/me/myfile) or unlink(/home/me/myfile) , the file can be deleted in my program. 更新:使用remove(/home/me/myfile)unlink(/home/me/myfile) ,可以在我的程序中删除该文件。

For a start, it's the permissions on the directory that control whether you can delete a file. 首先,它是控制是否可以删除文件的目录的权限。

But, having said that, there are numerous things that could be different between the two situations. 但是,话说回来,这两种情况之间可能有很多不同之处。 Your program might be running as a different user (such as with the SETUID bit), the path may be different, leading to a different rm being run, the program may set up a chroot jail so that it can no longer even see the file (though that may manifest as a different error), and so forth. 您的程序可能作为不同的用户运行(例如使用SETUID位),路径可能不同,导致运行不同的rm ,程序可能会设置chroot jail,以便它甚至不能再看到文件(尽管这可能表现为不同的错误),等等。 The possibilities are rather large. 可能性相当大。

However, C provides a call to delete files, called unlink - you should use that in preference and then check errno . 但是,C提供了一个删除文件的调用,称为unlink - 你应该优先使用它,然后检查errno

I would suggest checking the output of which rm in both cases, along with the full details of the file and executable, owner and permissions. 我建议在两种情况下检查which rm的输出,以及文件和可执行文件,所有者和权限的完整详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM