Linux c++系统命令失败

System command failing on Linux C++

本文关键字:失败 系统命令 c++ Linux      更新时间:2023-10-16

在我的程序中,我将一个可执行文件从一个位置复制到另一个位置,然后执行复制的文件。当复制的文件被执行时,我得到一个"拒绝许可"的错误。但是如果我重新启动我的程序,那么这个文件就会毫无问题地执行。有人能帮我解决这个问题吗?下面的代码很简单,但是演示了这个问题。

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',并且在运行该程序之后,目标也具有相同的访问权限。我可以手动执行它。之后的每一次程序运行都是成功的。为什么第一次运行就失败了?

你应该关闭你创建的文件。

参见cplusplus.com: std::ifstream::close

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