Linux c++系统命令失败
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',并且在运行该程序之后,目标也具有相同的访问权限。我可以手动执行它。之后的每一次程序运行都是成功的。为什么第一次运行就失败了?
你应该关闭你创建的文件。
参见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
相关文章:
- 提供变量作为 MATLAB 系统命令的输入参数,以便C++可执行文件
- 将系统命令打印到文本文件 C++
- 使用系统命令时发送输入不起作用
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- 如何将 c ++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?
- 加速安装失败:系统找不到指定的路径
- 来自C 应用程序的运行系统命令与Commandline不同
- CPP中的管道内部(AWK)系统命令
- C++:如何运行一个系统命令N次(异步)并返回N次执行时间
- 使用 C++ 更改注册表值?(系统命令失败)
- 使用系统命令调用可执行文件
- c++系统命令
- 如何在C++中通过将每个命令分配给线程来同时执行linux系统命令
- C++函数系统(命令)的输出在Linux终端中不显示颜色
- 使用Windows技术检测复制,粘贴,打印系统命令
- 使用系统命令从 Windows 下的 C 程序内部更改目录
- 有没有办法以给定的优先级执行系统命令
- 在Qt创建器运行系统命令中
- 如何使用system()在c中执行2个成功的系统命令,例如连接到ftp并使用程序登录
- Linux c++系统命令失败