2015-02-23 53 views
0
if(cmds.at(i)==">") 
{ 
      //convert strings to char*s 
      char* conversion = new char[cmds.at(i-1).size()+1]; 
      copy(cmds.at(i-1).begin(),cmds.at(i-1).end(),conversion); 
      conversion[cmds.at(i-1).size()] = '\0'; 
      const char * out_file_cstring = cmds.at(i+1).c_str(); 

      //count and agregate arguments 
      int size = count_arguments(conversion); 
      size++; 
      char** args= new char*[size];//dont forget to delete 
      args[0] = strtok(conversion," \n"); 
      for(int j = 1; j<size; j++){args[j] = strtok(NULL, " \n");} 
      args[size-1]= NULL; 

      //forking and redirection 
      int out_file = open(out_file_cstring,O_CREAT|O_WRONLY|O_TRUNC); 
      pid_t pid = fork(); 
      if(!pid) 
      { 
       dup2(out_file,STDOUT_FILENO); 
       close(out_file); 
       int r = execvp(args[0],args); 
       if(r<0) 
       { 
         cerr<<"ERROR : exec failed"<<args[0]<<endl; 
         return false; 
       } 
} 

所以我的代碼創建並正確寫入out_file。但是,由於某種原因該文件是可執行文件。我認爲這個錯誤是在我的open()調用中,但我似乎無法找到原因。系統調用open()創建可執行文件

回答

1

man 2 open解釋了原因:

int open(const char *pathname, int flags); 
int open(const char *pathname, int flags, mode_t mode); 

O_CREAT: 
If the file does not exist it will be created. [...] 
The permissions of the created file are (mode & ~umask). 

所以,如果你想有一個文件,該文件不是可執行文件,您可以使用:

open(out_file_cstring,O_CREAT|O_WRONLY|O_TRUNC, 0666); 

0666會建議所有的讀/寫(相當於常量標誌S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH),用戶的umask將進一步限制用戶選擇的默認權限。