C中的文件描述符错误

时间:2014-06-07 06:22:28

标签: c pipe

我正在尝试为C程序编写代码:在父进程中给出命令,然后通过管道将其发送到子进程,该进程处理命令。

响应是: write():错误的文件描述符

我想我没有关闭管道的错误端...不再确定了。有什么想法吗?

以下是代码:

  int main (int argc, char **argv) {

  ...

  int filedes[2];       

  if (pipe (filedes) < 0)
    error_fatal ("pipe ()");

  if ((pid = fork ()) < 0)
    error_fatal ("fork ()");
  else
    if (pid == 0) {

      if (close (filedes[0]) < 0)
    error_fatal ("close ()");

      while (1) {

      FD_ZERO (&read_set);
      FD_SET (filedes[1], &read_set);

    sleep (3);

    if (select (filedes[1] + 1, &read_set, NULL, NULL, NULL) < 0)
      error_fatal ("select ()");
    else {

      if (FD_ISSET (filedes[1], &read_set)) {

        if (read (filedes[1], &d, 1) != 1)
          error_fatal ("read ()");
        else
          if (d == EOF)
        break;
        else {

          switch (d) {

        case 'd' : if (system ("date") < 0) error_fatal ("system ()"); break;
        case 'u' : if (system ("users") < 0) error_fatal ("system ()"); break;
        default: printf ("No such command.\n"); break;
          }
        }
      }
    }
      }
    }
    else {

      if (close (filedes[1]) < 0)
    error_fatal ("close ()");

      while ((c = fgetc (stdin)) != EOF) {

    if (write (filedes[0], &c, 1) < 0)
      error_fatal ("write ()");

      }
    }

  exit (EXIT_SUCCESS);
}

0 个答案:

没有答案
相关问题