c - 使用管道在进程之间发送字符串

标签 c pipe

我正在尝试将代码从 C# 重写为 C,但遇到了一些麻烦。

所以我有一个名为 test 的文件,其中有一行文本。我想读取该行,通过进程之间的管道发送并将其打印在屏幕上。

代码如下:

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


void
read_from_pipe (int file)
{
  FILE *stream;
  int c;
  stream = fdopen (file, "r");
  while ((c = fgetc (stream)) != EOF)
    putchar (c);
  fclose (stream);
}

void
write_to_pipe (int file)
{
  FILE *stream;
  FILE *testfile;
  stream = fdopen (file, "w");
  testfile = fopen("test.txt", "r");
  char *line = NULL;
  size_t len = 0;
  //ssize_t read;
  getline(&line, &len, testfile);
  fprintf (stream, "%s", line);
  free(line);
  fclose(testfile);
  fclose (stream);
}

int
main (void)
{
  pid_t pid;
  int mypipe[2];


  if (pipe (mypipe))
    {
      fprintf (stderr, "Pipe failed.\n");
      return EXIT_FAILURE;
    }
  pid = fork ();
  if (pid == (pid_t) 0)
    {
      close (mypipe[1]);
      read_from_pipe (mypipe[0]);
      return EXIT_SUCCESS;
    }
  else if (pid < (pid_t) 0)
    {
      fprintf (stderr, "Fork failed.\n");
      return EXIT_FAILURE;
    }
  else
    {
      close (mypipe[0]);
      write_to_pipe (mypipe[1]);
      return EXIT_SUCCESS;
    }
}

但是,我在运行此代码时似乎遇到了段错误。我有什么遗漏的吗?

最佳答案

一旦您创建了 test.txt 文件,它可能会正常工作。 至少在我的机器上修复了它。

在 C 语言中,您通常需要进行一些相当繁琐的错误检查才能健壮地编写程序。例如,您应该编写如下内容:

int read_from_pipe (int file) {
  FILE *stream;
  int c;
  if((stream = fdopen (file, "r"))==NULL) goto err;

  while ((c = fgetc (stream)) != EOF){
    putchar (c);
  }
  if(ferror(stream)){ int er=errno; fclose (stream); errno=er; goto err; }
  return 0;
err:
  perror("read"); return -errno; 
}

等等

测试文件的 fopen 行如下所示:

if(!(testfile = fopen("test.txt", "r"))) { perror("write"); return -errno; }

您可能会收到一条很好的“写入:没有这样的文件或目录”消息。

关于c - 使用管道在进程之间发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954850/

相关文章:

c - 单个 sqrt() 的运行速度如何比放入 for 循环时慢两倍

sockets - IPC速度及比较

bash - 为什么重定向(<)不创建子shell

c - size_t modulo long unsigned int 的意外结果

c - 求C中两个数的LCM

c - 嵌入式 linux 编程入门套件

c - Linux内核中嵌入锁的动态分配/释放结构

c++ - 如何从 QT (C++) 中的子进程联系父进程以从类执行方法?

batch-file - 使用脱字符号 (^) 拆分长命令不适用于批处理文件中的管道 (|)

c - C 中的管道、复制、关闭和执行出现问题