[英]System command failing on Linux C++
在我的程序中,我將一個可執行文件從一個位置復制到另一個位置,然后執行復制的文件。 執行復制的文件后,出現“權限被拒絕”錯誤。 但是,如果我重新啟動程序,則文件將被執行而不會出現問題。 有人可以幫我解決這個問題嗎? 下面的代碼很簡單,但是演示了該問題。
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”,並且在運行該程序之后,目標位置也具有相同的訪問權限。 我可以手動執行它。 程序的每個后續運行均成功。 為什么第一次運行失敗?
您應該關閉已創建的文件。
Coderz,不知道您的IDE遇到什么問題,但這對我來說很好。
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
using namespace std;
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");
if (mkdir("./exe_dir", S_IRWXO | S_IRWXU | S_IRWXG))
perror("mkdir");
copyFile(original, dest_file);
if (chmod("./exe_dir/exefile", S_IRWXU | S_IRWXG | S_IRWXO) == -1)
perror("chmod");
return system("./exe_dir/exefile");
}
請注意,exe_file是一個簡單的Hello World二進制文件,結果為
sh: 1: ./exe_dir/exefile: not found
Hello World
復制的文件在哪里
-rwxrwxrwx 1 duck duck 18969 May 9 19:51 exefile
在目錄內
drwxrwxr-x 2 duck duck 4096 May 9 19:51 exe_dir
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.