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
, exec
和dup
但我不太知道如何将它们放在一起......
有人可以帮我解决这个问题吗?
最佳答案
作为一个简单的示例,这应该可以让您简要了解这些系统调用如何协同工作。
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/