C:execlp()和>;

C:execlp()和>;,c,bash,C,Bash,我想从C文件运行execlp(),并将结果写入某个输出文件。 我用这句话: buff = "./cgi-bin/smth"; execlp(buff, buff, "> /cgi-bin/tmp", NULL); 其中smth是一个已编译的c脚本。 但是smth打印到标准输出,并且没有显示任何文件。 发生了什么,以及如何将脚本结果放入输出文件?如果使用execlp,则必须使用dup2自己处理。您可以比较一下我如何使用execvp处理文件。我为out重定向传递一个标志,然后处理它: i

我想从C文件运行execlp(),并将结果写入某个输出文件。 我用这句话:

buff = "./cgi-bin/smth";
execlp(buff, buff, "> /cgi-bin/tmp", NULL);
其中smth是一个已编译的c脚本。 但是smth打印到标准输出,并且没有显示任何文件。
发生了什么,以及如何将脚本结果放入输出文件?

如果使用
execlp
,则必须使用
dup2
自己处理。您可以比较一下我如何使用
execvp
处理文件。我为out重定向传递一个标志,然后处理它:

  if (structpipeline->option[0] == 1) { /* output redirection */    
        int length = structpipeline[i].size;
        char *filename = structpipeline->data[length - 1];
        for (int k = length - 2; k < length; k++)
            structpipeline->data[k] = '\0';    
        fd[1] = open(filename, O_WRONLY | O_CREAT, 0666);
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);
    } /* TODO: input redirection */
    execvp(structpipeline[i].data[0], structpipeline[i].data);
if(structpippeline->option[0]==1){/*输出重定向*/
int length=structpipeline[i]。大小;
char*filename=structpipeline->data[length-1];
for(int k=length-2;k数据[k]='\0';
fd[1]=打开(文件名,O|u WRONLY | O|u CREAT,0666);
dup2(fd[1],标准文件号);
关闭(fd[1]);
}/*TODO:输入重定向*/
execvp(structpipeline[i].data[0],structpipeline[i].data);
另见这个问题

“发生了什么?”-运行程序
/cgi-bin/smth
,第0个参数是
/cgi-bin/smth
,第一个参数是
/cgi-bin/tmp
。您要求发生的事情正好发生了。shell为您执行I/O重定向;如果你在写“shell”,你必须自己写。最简单的修复方法是使用
系统(“./cgi-bin/smth>/cgi-bin/tmp”)(您确定文件不应该是
/cgi-bin/tmp
?)。否则,您必须在程序中打开该文件,并安排标准输出到该文件-使用
dup2()
close()
open()
,而不是按该顺序。不遵守shell样式的重定向、扩展,在处理不受信任的数据时,直接调用
exec*
-family系统调用要比通过
system()
更安全,这也是shell特有的另一种魔力。如果这不是您在这里描述的方式,那么在UNIX上编写安全软件几乎是不可能的。