0

我正在尝试使用 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)

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

提前谢谢。

4

1 回答 1

4

你写了

close (fd2[1] != -1)

就像fd2[1]3 或 5 或其他什么一样,fd2[1] != -1评估为 1 并且您执行close(1).

我想你宁愿

close (fd2[1]) != -1
于 2013-11-11T12:48:00.093 回答