cmd输入输出重定向

command 1> (标准输出 cout
command 2> (错误输出 cerr 和 clog

例子:可执行文件里依次是
cout cerr clog
cmd 1>a.txt 2>&1
将标准输出和错误输出全部输入到a.txt中

作用等于 cmd 2>a.txt 1>&2

命令的组合顺序不影响
cmd里无论是先cout 还是先cerr都不影响实际的cout和cerr

cout和cerr指向同一个输出文件
cmd 1>a.txt 2>&1
cmd 2>a.txt 1>&2

在文件中追加内容
cmd 1>>a.txt 2>>&1

转载于:https://www.cnblogs.com/shawnchou/p/10934315.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是实现输入定向和输出定向的代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #define MAX_CMD_LEN 256 int main() { char cmd[MAX_CMD_LEN]; char *args[MAX_CMD_LEN]; char *input_file, *output_file; int input_fd, output_fd; int i, j; while (1) { printf("myshell> "); fgets(cmd, MAX_CMD_LEN, stdin); // 读取命令行输入 if (feof(stdin)) { // 用户输入Ctrl+D,退出程序 printf("\n"); break; } // 解析命令行参数 args[0] = strtok(cmd, " \n"); i = 1; while ((args[i] = strtok(NULL, " \n")) != NULL) { i++; } args[i] = NULL; // 查找输入输出定向符号 input_file = NULL; output_file = NULL; for (j = 0; j < i; j++) { if (strcmp(args[j], "<") == 0) { // 输入定向符号 input_file = args[j+1]; args[j] = NULL; break; } if (strcmp(args[j], ">") == 0) { // 输出定向符号 output_file = args[j+1]; args[j] = NULL; break; } } // 执行命令 pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // 子进程 // 输入定向 if (input_file != NULL) { input_fd = open(input_file, O_RDONLY); if (input_fd == -1) { perror("open input file"); exit(1); } if (dup2(input_fd, STDIN_FILENO) == -1) { perror("dup2 input"); exit(1); } close(input_fd); } // 输出定向 if (output_file != NULL) { output_fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (output_fd == -1) { perror("open output file"); exit(1); } if (dup2(output_fd, STDOUT_FILENO) == -1) { perror("dup2 output"); exit(1); } close(output_fd); } // 执行命令 execvp(args[0], args); perror(args[0]); exit(1); } else { // 父进程 waitpid(pid, NULL, 0); } } return 0; } ``` 在上述代码中,我们首先解析用户输入的命令行参数,查找输入输出定向符号 `<` 和 `>`,并分别获取输入输出文件名。接着,在子进程中,我们使用 `open()` 函数打开输入输出文件,并使用 `dup2()` 函数将标准输入或标准输出定向到文件描述符。最后,我们使用 `execvp()` 函数执行用户输入的命令。在父进程中,我们使用 `waitpid()` 函数等待子进程结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值