【问题标题】:pipe 2 linux commands in c [duplicate]c中的管道2 linux命令[重复]
【发布时间】:2011-06-15 22:42:45
【问题描述】:

可能重复:
Is it possible to have pipe between two child processes created by same parent (LINUX, POSIX)

我想用 C 创建一个程序。这个程序必须能够执行与管道 2 linux 命令相同的操作。 例如: ps aux | grep ssh

我需要能够在 c 脚本中执行此命令。

我知道我可以使用 forkpipeexecdup,但我不太知道如何将它们组合在一起...... 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你走了多远?你能告诉我们一些你写的代码吗?
  • 您只是希望您的程序能够在管道中工作吗?然后只需从stdin 读取并写入stdout,您就会自动获得该行为。

标签: c pipe


【解决方案1】:

作为一个简单的例子,这应该让您简要了解这些系统调用如何协同工作。

void spawn(char *program,char *argv[]){    
     if(pipe(pipe_fd)==0){
          char message[]="test";
          int write_count=0;

          pid_t child_pid=vfork();

          if(child_pid>0){
               close(pipe_fd[0]); //first close the idle end
               write_count=write(pipe_fd[1],message,strlen(message));
               printf("The parent process (%d) wrote %d chars to the pipe \n",(int)getpid(),write_count);
               close(pipe_fd[1]);
          }else{
               close(pipe_fd[1]);
               dup2(pipe_fd[0],0);

               printf("The new process (%d) will execute the program %s with %s as input\n",(int)getpid(),program,message);
               execvp(program,argv);
               exit(EXIT_FAILURE);
          }
     }
}

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 2015-05-19
    • 2017-05-08
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多