c中的pipe 2 linux命令
可能重复:c中的pipe 2 linux命令,c,pipe,C,Pipe,可能重复: 我想用C语言创建一个程序。这个程序必须能够执行与Piping2 linux命令相同的操作。 例如: ps aux|grep ssh 我需要能够在c脚本中执行此命令 我知道我可以使用,fork,pipe,exec和dup但我不太知道如何将它们组合在一起。。。 有人能帮我吗?作为一个简单的例子,这应该能让您简要了解这些系统调用是如何协同工作的 void spawn(char *program,char *argv[]){ if(pipe(pipe_fd)==0){
我想用C语言创建一个程序。这个程序必须能够执行与Piping2 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);
}
}
}
你走了多远?你能给我们看看你写的一些代码吗?你只是希望你的程序能够在管道中工作吗?然后只需从
stdin
读取数据,然后写入stdout
,您就会自动获得该行为。