c - C语言中的pipe 2 linux命令

标签 c pipe

Possible Duplicate:
Is it possible to have pipe between two child processes created by same parent (LINUX, POSIX)

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

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

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

最佳答案

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

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);
          }
     }
}

关于c - C语言中的pipe 2 linux命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6365303/

相关文章:

python - 在 sys.stdin.read() 和子进程调用 vim 之后如何不弄乱终端?

c - 如何在不使其成为全局的情况下共享硬件抽象结构

c - 如何在 C 和 Linux 中检查套接字的可用数据量

C fork 不起作用

bash - 当进程不存在时管道到进程?

python - 让 readline 在 FIFO 上阻塞

c - 从 C 获取 Lua 字符串

c - 动态数组中的垃圾值

string - 如何获取管柱长度?

c++ - 项目组织的最佳方式是什么?