在linux shell中的管道命令机制,如下面shell命令
caojiangfeng@caojiangfeng-laptop:~$ls -l grep test
-rwxr-xr-x 1 caojiangfeng caojiangfeng 8548 2010-03-11 21:48 test
-rw-r--r-- 1 caojiangfeng caojiangfeng 1484 2010-03-11 21:48 test.c
下面程序模拟上面shell中的命令执行过程
#include
int main()
{
int pipefd[2];//存放管道文件句柄
int p1 = 0,p2 = 0;
char *arg1[] = {"/bin/ls","-l",NULL};
char *arg2[] = {"/bin/grep","test",NULL};
if (pipe(pipefd) == -1) { /*pipe()创建管道,pipefd[]中分别是读、写端的文件句柄*/
printf("Create pipe failed!\n");
exit(-1);
}
if (!(p1=fork())){ /*建立子进程运行"ls -l"*/
close(pipefd[0]);/*关闭子进程中的管道文件的读端*/
close(1);/*关闭原标准输出*/
dup(pipefd[1]);/*将标准输出指向管道文件的写端*/
close(pipefd[1]);
execve("/bin/ls",arg1,NULL);/*运行"ls -l"*/
/*子进程执行系统调用execve后,一般是不会返回到这里的,除非出现了错误*/
printf("If this memssage shows,something must be wrong!\n");
}
close(pipefd[1]);/*关闭父进程中的写端*/
if (!(p2 = fork())) {//建立运行grep test
close(0);/*关闭原标准输入*/
dup(pipefd[0]);/*标准输入指向管道文件的读端*/
close(pipefd[0]);
/*子进程p2运行"greptest",它将p1的输出当做其输入内容来读*/
execve("/bin/grep",arg2,NULL);/*运行"ls -l"*/
/*子进程执行系统调用execve后,一般是不会返回到这里的,除非出现了错误*/
printf("If this memssage shows,something must be wrong!\n");
}
/*父进程等待子进程全部退出后再结束*/
wait4(p1,NULL,0,NULL);
wait4(p2,NULL,0,NULL);
printf("The process complete!\n");
return 0;
}
caojiangfeng@caojiangfeng-laptop:~$gcc -o test test.c
caojiangfeng@caojiangfeng-laptop:~$./test
caojiangfeng@caojiangfeng-laptop:~$ls -l grep test
-rwxr-xr-x 1 caojiangfeng caojiangfeng 8548 2010-03-11 21:48 test
-rw-r--r-- 1 caojiangfeng caojiangfeng 1484 2010-03-11 21:48 test.c
阅读(786) | 评论(0) | 转发(0) |