c - 管道实现中的错误,我面临这个错误,ls : write error: Bad file descriptor

标签 c fork pipe

我在c中实现shell时做了这个,但是尽管在实现管道时,我遇到了这个错误ls:write error:Bad file detector,而且我不明白为什么会出现这个错误, 请帮忙。

#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
void  execute(char **argv)
{
  pid_t  pid;
  int    status;
  //fflush(0); 
  pid_t id  ;
  int out=0,in=0,pip=0;
  int fds[2];

  if ((pid = fork()) < 0) {     /* fork a child process           */
      printf("*** ERROR: forking child process failed\n");
      exit(1);
  }
  if (pid==0) {
    close(1);       /* close normal stdout */
    dup2(fds[1],1);   /* make stdout same as pfds[1] */
    close(fds[0]); /* we don't need this */
    execlp(argv[0],argv[0],argv[1],NULL);
   } 
  else {
     close(0);       /* close normal stdin */
     dup2(fds[0],0);   /* make stdin same as pfds[0] */
     close(fds[1]); /* we don't need this */
     execlp(argv[3],argv[3],argv[4], NULL);
    }


  }

最佳答案

在调用 fork() 之前,您似乎错过了对 pipe(fds); 的调用。您还缺少一些 close() 调用。如果将管道的一端(使用 dup()dup2())复制到标准输入或标准输出,则应关闭两者来自 pipe() 的原始描述符。

还有一个强有力的论点是您应该检查系统调用的返回值。您可以使用这样的函数:

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

extern void err_exit(const char *fmt, ...);

void err_exit(const char *fmt, ...)
{
    int errnum = errno;
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    if (errnum != 0)
        fprintf(stderr, " (%d: %s)", errnum, strerror(errnum));
    fputc('\n', stderr);
    exit(1);
}

您可以像这样使用它:

if (dup2(fds[2], 1) != 0)
    err_exit("dup2(%d, %d) failed", fds[2], 1);

关于c - 管道实现中的错误,我面临这个错误,ls : write error: Bad file descriptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428267/

相关文章:

c - 在函数中传递结构

c++ - 内核驱动程序读取内存未发送整个字符串

c++ - 错误 C3861 : '_tcsdup' : identifier not found

linux - 使 ExecStartPost 命令在后台运行

linux - 使用管道在 awk 语句中输入

c++ - 初始化 Vanilla C 结构

linux - Root 守护进程-> 模拟为较小的用户-> 派生一个 child 。子进程是用户还是有一些root权限?

c - SIGPIPE中一个简单的二进程程序

email - 将电子邮件传送到解析器脚本时获取 "Error in argument 1, char 3: option not found"

c - 我收到错误 : petition of a member in something that it's not an structure or an enum in C