【发布时间】:2013-05-02 04:22:57
【问题描述】:
在我的程序中,我将一个可执行文件从一个位置复制到另一个位置,然后执行复制的文件。执行复制的文件时,我收到“权限被拒绝”错误。但是如果我重新启动我的程序,那么文件就会毫无问题地执行。有人可以帮我解决这个问题吗?下面的代码很简单,但演示了问题。
void copyFile(string _from, string _to)
{
std::ifstream src(_from.c_str());
std::ofstream dst(_to.c_str());
dst << src.rdbuf();
}
int main()
{
string original("./exe_file");
string dest_file("./exe_dir/exefile");
system("./exe_dir/exefile"); //Fails on first run because exe_dir does not exist.
//mkdir and copy the file.
mkdir("./exe_dir",S_IRWXO | S_IRWXU | S_IRWXG);
copyFile(original, dest_file);
//Open the file and close it again to flush the attribute cache.
int fd = open(dest_file.c_str(),O_RDONLY);
close(fd);
//The line below fails with system error code 2 (Permission denied) on exefile.
return system("./exe_dir/exefile");
{
在执行程序之前,我在原始文件上使用了“chmod 777 exe_file”,并且在运行该程序后,目标也具有相同的访问权限。我可以手动执行它就好了。并且程序的每次后续运行都是成功的。为什么第一次运行就失败了?
【问题讨论】:
-
如果
exe_dir在您调用system时存在,那么mkdir如何工作? -
最初不存在。它将在第一次运行之后。在这种情况下,mkdir 将在第二次运行时失败,但不会影响执行,因为它只会返回一个被忽略的错误代码。
-
复制的exe文件没有执行权限。执行 chmod 或任何最适合您的方法。
-
我试过
chmod(dest_file.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)。我还尝试在执行系统命令之前统计文件并刷新属性缓存。我正在尽我所能确保权限正确,但仍然失败。 -
以上链接(
umask):en.wikipedia.org/wiki/Umask