Linux系统编程:dup2()重定向

本文介绍了Linux系统编程中的dup2()函数,通过实例解析其功能,特别是重定向标准输出和标准输入的效果。通过代码演示,区分了dup2(fd, 0)与dup2(0, fd)的区别,前者实现输入重定向,后者改变fd指向,导致程序进入交互模式。" 53160914,5638124,Matlab深度学习实践:车辆检测与车型识别,"['深度学习', '图像识别', 'Matlab', 'AlexNet', '车辆检测']
摘要由CSDN通过智能技术生成

对于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);

}


加入了2printf ,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值