【问题标题】:writing stdout to a file from execvp从 execvp 将标准输出写入文件
【发布时间】:2014-03-18 08:57:18
【问题描述】:

为什么 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

【问题讨论】:

  • 显示不工作的实际打印。
  • execvp 执行时,它的输出应该到 fd,但它似乎哪儿也不去。那是行不通的。如果我在 printf 之前删除 cmets,我的文件包含“这是一个测试\n”。
  • subcommand 是如何填充的?
  • 这是我正在编写的 shell 中的一个 sn-p 代码。如果我输入“grep hamster > a”,那么子命令将只是 {“grep”,“hamster”} 用于测试,我使用的是 ls > a,所以子命令将是 {“ls”}。 makesubcommand(4) 已经过测试并且可以正常工作。
  • 我做了一些编辑,使我的代码更加透明,并添加了一些发送到 stderr 的调试消息。仍在寻找解决方案,但我确实认为问题出在子命令中:(

标签: c redirect fork execvp dup2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2012-06-01
    • 2018-12-07
    • 2011-04-09
    • 2017-06-03
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多