c++ - execve 函数在 C++ 中总是失败
问题描述
我有一个分叉两个孩子的程序。
第一个子目录列出主目录内容并将其保存在一个文本文件中,并创建两个目录,一个用于保存 c++ 文件,一个用于保存文本文件。
第二个孩子使用该execve
函数执行另一个名为arrange_files
. 该程序读取ls
命令产生的文本文件,并将 cpp 文件移动到 cfiles 目录,将文本文件移动到 txtfiles 目录
我是 C++ 新手,问题是 execve
总是返回 -1 的系统调用
这是 parent.cpp
#include<iostream>
#include<sys/wait.h>
#include <unistd.h>
using namespace std;
int main()
{
pid_t child1,child2;
child1 = fork();
if(child1==0){
//child 1 code
system("ls >> Myfiles.txt");
system("mkdir Cfiles");
system("mkdir txtfiles");
}
else if(child1>0)
{
// this is parent
child2 =fork();
wait(NULL);
if(child2==0){
//child 2 code
char * args[2];
string st = "./arrange_files";
args[0]= (char *) st.c_str();
args[1]= NULL;
if(execve("./arrange_files", args ,NULL)==-1)
cout<<"Somthing went wrong!"<<endl;
}
}// end of else
return 0;
}
这是arrange_files.cpp
#include<iostream>
#include<fstream> // include the fstream (file stream library)
#include<string>
using namespace std;
int main()
{
// declaring an input file called infile
ifstream infile;
// opening the input file (file we will read from) that called myfiles.txt
infile.open("Myfiles.txt");
string line;
// loop to read the content of the file line by line till the end of the file
while(getline(infile,line))
{
if(line.find("txt") != string::npos){
string command= "mv " +line + " txtfiles";
system(command.c_str());
}
else if(line.find("cpp")!= string::npos){
string command= "mv " +line + " Cfiles";
system(command.c_str());
}
infile.close();
}//end of while loop
return 0;.
}// end of the program
解决方案
推荐阅读
- python-2.7 - 我的计数矢量化器代码运行完美,标记“utf8”错误,没有结构变化
- api - 我可以让我的设备(闹钟)在 Google 家庭音响上播放音频文件吗
- facebook - 打开图形对象调试器在同时具有标题和对象标签时给出错误?
- rest - Flutter 中的简单 GET API 请求
- node.js - 反应:不知道如何使用复选框选择表行并使用 node.js 将值发送到服务器端
- java - 'java.lang.NumberFormatException: Invalid double' 用于欧洲语言,使用 Kotlin
- android - 如何避免 Android TalkBack 读取 SwitchCompat TextOn/TextOff
- html - 如何找出动态链接可以采用哪些参数?
- python - 具有复数的 Python interp2D
- matlab - 如何在matlab中使用if来处理2个矩阵条件?