c - 通过管道传递变量,通过 fork 进程执行 Shell 命令

标签 c linux pipe fork

这是一种无法实现的特殊场景。我想了解我在做什么错误。

场景:
1.fork一个子进程 2. 子进程应该执行一个shell命令(例如cat sort a file) 3. shell 命令的参数通过管道从父进程传递(例如,g.cat 排序的文件输入)

我已经编写了下面的程序但是它显示的是文件名而不是打印出文件内容。但是它挂起而没有在屏幕上提供任何输出

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(){

  int pipefd[2];
  pipe(pipefd);

  //create a pipe before you fork a child process
  pid_t cpid = fork();
  if(cpid < 0){
    perror("Fork");
  }
  else if(cpid == 0){
    printf("This is child process\n");

    close(pipefd[1]);
    close(0);

    dup2(pipefd[0],0);

    execlp("sort", "sort", NULL);

    exit(0);

  }
  else{
    printf("This is parent process\n");
    close(pipefd[0]);

    char *sort_array[] = {"hello", "amigos", "gracias", "hola"};
    for (int i=0; i<4; i++){
      write(pipefd[1],sort_array[i],strlen(sort_array[i]));
      write(pipefd[1], "\n",1);
    }


    int cstatus;
    wait(&cstatus);

  }


}

更新:
原始示例无效。我已更新排序命令。
我正在尝试对内容进行排序。但是屏幕一直挂着,没有任何输出

最佳答案

当您使用 dup 时,您使用管道输入模拟子进程 stdin 因此当您执行 sort 时不带任何参数,它是从 stdin 并读取直到看到 EOF,因此您必须写入管道然后关闭它。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(){

   int pipefd[2];
   //create a pipe before you fork a child process
   pipe(pipefd);

   pid_t cpid = fork();
   if(cpid < 0){
       perror("Fork");
   } else if(cpid == 0) {
       printf("This is child process\n");

       close(pipefd[1]);
       close(0);

       dup2(pipefd[0],0);

       execlp("sort", "sort", NULL);

       exit(0);

  } else {
      printf("This is parent process\n");
      close(pipefd[0]);

      char *sort_array[] = {"hello", "amigos", "gracias", "hola"};
      for (int i=0; i<4; i++){
          write(pipefd[1],sort_array[i],strlen(sort_array[i]));
          write(pipefd[1], "\n",1);
      }
      close(pipefd[1]);


      int cstatus;
      wait(&cstatus);

    }
}

关于c - 通过管道传递变量,通过 fork 进程执行 Shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490341/

相关文章:

c - 用 C 读取高分/分析字符串

c -/proc 目录是根据请求动态生成的吗?

c - 为什么我的 insert_node 函数会删除我的根? (C)

c - 这个无括号/无括号代码如何有效?

c - C语言读取一个TXT文件中的所有字符

更改用户 ID 以分配附加功能

Linux - 如何从/proc/devices 中删除条目

python - 需要避免没有通信的子进程死锁

go - 如何使用 Pipes 分配额外的 ExraFile 以拥有多个输出流?

c - 管道和 fork ,不显示在标准输出上