【问题标题】:C program to print home directory showing "grep: (standard input): Bad file descriptor"打印主目录的 C 程序显示“grep:(标准输入):错误的文件描述符”
【发布时间】:2017-10-27 20:56:40
【问题描述】:

运行以下代码时,我收到“grep: (standard input): Bad file descriptor”。知道为什么吗?该程序应该打印出您的主目录。谢谢!

#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void) {
pid_t childpid;
int fd[2];

if(pipe(fd) == -1) { /* setup a pipe */
    perror("Failed to setup pipeline");
    return 1;
}
if((childpid = fork()) == -1){ /* fork a child */
    perror("Failed to fork a child");
    return 1;
}
if(childpid == 0){ /* env is the child */

    if(dup2(fd[1],STDOUT_FILENO)==-1)
        perror("Failed to redirect stdout of env");
    else if(close(fd[0] == -1)) /* close unused file descriptor */
        perror("Failed to close extra pipe descriptors on env");
    else {
        execl("/usr/bin/env", "env", NULL); /* execute env */
        perror("Failed to exec env");
    }
    return 1;
}
if(dup2(fd[0],STDIN_FILENO)==-1) 
/*grep is the parent*/
    perror("Failed to redirect stdin of grep");
else if(close(fd[1]==-1))
    perror("Failed to close extra pipe file descriptors on grep");
else {
    execl("/bin/grep", "grep", "HOME", NULL); /*execute "grep HOME"*/
    perror("Failed to exec grep");
}
return 1;
}

【问题讨论】:

  • 在第一个测试中,应该是 if(pipe(fd[0]) == -1) {} 吗?因为 fd 的地址不是合适的描述符
  • grep HOME 到底是做什么的?你在那里缺少文件名吗?

标签: c grep pipe file-descriptor


【解决方案1】:

错误在这两行:

else if(close(fd[0] == -1))
...
else if(close(fd[1]==-1))

应该是:

else if(close(fd[0]) == -1)
...
else if(close(fd[1]) == -1)

否则不执行外部程序就可以实现获取HOME env:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv, char** envp)
{
    char** env;
    for (env = envp; *env != 0; env++)
    {
        char* thisEnv = *env;
        if (strncmp(thisEnv, "HOME=", 5) == 0)
        {
            printf("%s\n", thisEnv + 5);
            break;
        }
    }
    return(0);
}

【讨论】:

  • #include &lt;stdlib.h&gt; 和 const char *home = getenv("HOME"); 怎么样?
猜你喜欢
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多