首页 > 解决方案 > 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

标签: c++linuxforksystem-callsexecve

解决方案


推荐阅读