【问题标题】:system call open() creating executable系统调用 open() 创建可执行文件
【发布时间】:2015-02-23 20:09:32
【问题描述】:
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() 调用中,但我似乎找不到原因。

【问题讨论】:

    标签: c++ linux redirect tags system-calls


    【解决方案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 将进一步将最终权限限制为用户选择的默认值。

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 2016-10-27
      • 1970-01-01
      • 2015-04-20
      • 2022-11-02
      • 2015-06-02
      • 2015-08-17
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多