关闭文件描述符

时间:2013-11-11 11:54:21

标签: c process operating-system pipe

我正在尝试使用2个管道编写所谓的客户端 - 服务器程序,但是当我运行以下程序(server.c)时:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "err.h"

#define BUF_SIZE    1024

char message[] = "Hello from your parent!\n";
char response[] = ""; 
int main (int argc, char *argv[])
{
  int fd1 [2];
  int fd2 [2];  
  int buf_len;  
  if (pipe (fd1) == -1) syserr("Error in pipe\n");
  if (pipe (fd2) == -1) syserr("Error in pipe\n");

  switch (fork ()) {
    case -1: 
      syserr("Error in fork\n");

    case 0:

      if (close (0) == -1)       syserr("child, close (0)");
      if (dup (fd1 [0]) != 0)    syserr("child, dup (pipe_dsc [0])");
      if (close (fd1 [0]) == -1) syserr("child, close (pipe_dsc [0])");
      if (close (fd1 [1]) == -1) syserr("child, close (fd1 [1]");

      if (close (1) == -1)       syserr("child, close (1)");
      if (dup (fd2 [1]) != 1)    syserr("child, dup (pipe_dsc [1]"); 
      if (close (fd2 [1]) == -1) syserr("child, close (pipe_dsc [1])");
      if (close (fd2 [0]) == -1) syserr("chiled, close (fd2 [0]");

      execl("./client", "client", (char*) 0); 
      syserr ("child, execvp");

      exit (0);

    default:

      printf("%d\n", fd1[0]);
      printf("%d\n", fd1[1]);
      printf("%d\n", fd2[0]);
      printf("%d\n", fd2[1]);
      if (close (fd1[0] != -1)) syserr("parent, close (fd1[0])");
      if (close (fd2[1] != -1)) syserr("parent, close (fd2[1])");
      while (fgets(message, sizeof(message), stdin) != NULL) {
          if (write (fd1 [1], message, sizeof(message) - 1) == -1) 
              syserr("write");
          if ((buf_len = read(fd2[0], response, BUF_SIZE -1)) == -1) 
              syserr("Error in read");
          printf("%s%s", "response: ", response);
      }   

      if (close (fd1 [1]) == -1) syserr("parent, close (pipe_dsc [0])");
      if (close (fd2 [0]) == -1) syserr("parent, close (pipe_dsc [1])");

      if (wait (0) == -1)
          syserr("wait");
      exit (0);
  } /* switch (fork ()) */
}

和client.c

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include "err.h"

#define BUF_SIZE                1024

int main (int argc, char *argv[])
{
    char buf[BUF_SIZE];
    while (fgets(buf, sizeof(buf), stdin) != 0) {
        printf("%s%s","Write to stdout",  buf);
    }   
    return 0;
}

我犯了以下错误:

3
4
5
6
ERROR: parent, close (fd2[1]) (9; Bad file descriptor)

知道为什么我不能关闭描述符吗?

提前做好准备。

1 个答案:

答案 0 :(得分:4)

你写了

close (fd2[1] != -1)

由于fd2[1]为3或5或其他任何内容,fd2[1] != -1评估为1,您执行close(1)

我觉得你更想要

close (fd2[1]) != -1