0

为什么 execvp 没有写入重定向的 STDOUT?我尝试在这个块中使用 printf() 作为测试,它准确地写入了它应该写入的位置,即我将 STDOUT 重定向到的文件中。

编辑:我更改了代码,并添加了 makesubcommand 的实现,并添加了一些调试消息。

pid = fork();
    wait(0);
    if(pid == 0)
    {
        fd = open(subargs[next_redirect + 1], O_CREAT|O_TRUNC|O_WRONLY, 0644);
        dup2(fd, STDOUT_FILENO);
        close(fd);
        //create sub-command
        int val = (next_redirect - (last_redirect + 1));
        fprintf(stderr,"subcommand will have %i indexes\n", val);
        char* subcommand[val];
        makesubcommand(subcommand, subargs, last_redirect + 1, next_redirect);
        execvp(subcommand[0], subcommand);
        fprintf(stderr,"execvp failed\n");
    }
    last_redirect = next_redirect;
    next_redirect = getnextredirect(subargs, last_redirect+2, subargc);

继承人 makesubcommand(4):

void makesubcommand(char** newcommand, char** oldcommand, int lowerbound, int upperbound)
{
    int i;
    fprintf(stderr, "lowerbound: %i upperbound: %i\n",lowerbound, upperbound);
    for(i = lowerbound; i < upperbound; i++)
    {
        fprintf(stderr,"subarg[%i]: %s\n", (i-lowerbound), oldcommand[i]);
        newcommand[i - lowerbound] = oldcommand[i];
    }
    for(i = lowerbound; i < upperbound; i++)
    {
        fprintf(stderr, "newcommand[%i] = %s\n",(i - lowerbound), newcommand[i]);
    }
    fprintf(stderr, "it worked\n");
}

这是一个测试运行:

{12425}/home/chris/2240New/WMU-CS2240/A3_Shell$ ls > a
subcommand will have 1 indexes
lowerbound: 0 upperbound: 1
subarg[0]: ls
newcommand[0] = ls
it worked
execvp failed
4

1 回答 1

0

我的问题最终是我需要为子命令分配内存。malloc 成功了!

于 2014-03-18T16:35:49.807 回答