对于Dup2 的理解:
源代码:
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <time.h> 6 7 #define MSGSIZE 20 8 #define READ 0 9 #define WRITE 1 10 11 int main(int argc, char const *argv[]) 12 { 13 int p[2], bytes, res, c; 14 char inbuf[10240]; 15 int pid; 16 printf("%c", 11); 17 if(pipe(p) == -1){ // creat the pipe , if pipe is built failed , exit . 18 perror("pip call"); 19 exit(1); 20 } 21 pid = fork(); 22 if(pid != 0){ // creat parent pid and child pid. 23 close(p[READ]);//close parent pipe read 24 dup2(p[WRITE], 1); 25 close(p[WRITE]);//close parent pipe write 26 execlp(argv[1], argv[1], NULL); 27 } 28 else{ 29 30 close(p[WRITE]);//close child pipe write 31 32 dup2(p[READ],0); 33 34 close(p[READ]);//close child pipe read 35 36 execlp(argv[2], argv[2], NULL); 37 } 38 return 0; 39 }
通过命令行输出:
./a.out “ls” “ps”
仅仅在终端执行了ps的命令, 而没有看到ls 命令的结果。
因此,开始走入了第一个误区:父进程没有执行
通过调试 在父进程执行if条件中加入以下代码:
if(pid != 0){
printf("4556\n");
close(p[READ]);
dup2(p[WRITE], 1);
close(p[WRITE]);
printf("4556\n");
execlp(argv[1], argv[1], NULL);
}
加入了2个printf ,