c - 使用管道将多个字符串发送到子进程

标签 c linux fork pipe

我在 Linux 中有一个任务,但我无法让它工作。

我有一个接收文本文件作为参数的程序。然后,它使用 fork() 创建一个子进程,并将作为参数接收的文本文件的内容逐行发送到子进程。子进程需要统计行数并返回给父进程接收到的行数。

这是我到目前为止所拥有的,但有些子进程并没有收到所有的行。对于我的测试,我使用了一个包含 9 行的文本文件。父进程将 9 行作为字符串发送,但子进程只收到其中的 2 或 3 行。

我做错了什么?

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

int main(int argc, char *argv[])
{  
  char string[80];
  char readbuffer[80];
  int pid, p[2];
  FILE *fp;
  int i=0;
  if(argc != 2)
  {
    printf("Syntax: %s [file_name]\n", argv[0]);
    return 0;    
  }
  fp = fopen(argv[1], "r");
  if(!fp) 
  {    
    printf("Error: File '%s' does not exist.\n", argv[1]);
    return 0;
  }
  if(pipe(p) == -1)
  {
    printf("Error: Creating pipe failed.\n");
    exit(0);
  } 
  // creates the child process
  if((pid=fork()) == -1)
  {
   printf("Error: Child process could not be created.\n");
    exit(0);
  }  

  /* Main process */
  if (pid) 
  { 
    // close the read
    close(p[0]);    
    while(fgets(string,sizeof(string),fp) != NULL)
    {                
       write(p[1], string, (strlen(string)+1));
       printf("%s\n",string);
    } 

    // close the write
    close(p[1]);
    wait(0);
  }

  // child process
  else 
  {   
    // close the write
    close(p[1]); 

    while(read(p[0],readbuffer, sizeof(readbuffer)) != 0) 
    {
      printf("Received string: %s\n", readbuffer);    
    }

    // close the read
    close(p[0]); 
  } 
  fclose(fp);       
}

最佳答案

管道是一个单向的进程间通信 channel 。您必须创建 2 个管道,一个用于与子进程通信,另一个用于读回数据。

请记住在两个进程中关闭管道未使用的一侧。

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

相关文章:

c - Pthread 屏障和树莓派

c - 如果用户按除 1 或 2 或 3 之外的任意键,如何返回开头?

php - 在 PHP 中,如何测量请求使用硬盘的时间?

fork - 使用 fork 和 MPI 进行多进程编程的区别

c - sprintf 的奇怪工作

C 如果条件没有按预期工作

c - 为什么在 argc 和 argv 中传递参数的程序在以不同方式执行时会得到不同的结果

linux - 在 Azure DevOps Pipeline 中提供 SSH 私钥的最佳方式是什么?

c - 当我创建一个简单的进程树时出现奇怪的输出

fork - J语言熵公式