写入标准输入和读取标准输出(UNIX/LINUX/C 编程) [英] Writing to stdin and reading from stdout (UNIX/LINUX/C Programming)

查看:43
本文介绍了写入标准输入和读取标准输出(UNIX/LINUX/C 编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一项作业,其中程序将文件描述符作为参数(通常来自 exec 调用中的父级)并从文件中读取并写入文件描述符,在我的测试中,我意识到如果我使用 0、1 或 2 作为文件描述符,程序将在命令行中工作并且不会给出错误.这对我来说很有意义,只是我可以写入 stdin 并将其显示在屏幕上.

I was working on an assignment where a program took a file descriptor as an argument (generally from the parent in an exec call) and read from a file and wrote to a file descriptor, and in my testing, I realized that the program would work from the command-line and not give an error if I used 0, 1 or 2 as the file descriptor. That made sense to me except that I could write to stdin and have it show on the screen.

对此有解释吗?我一直认为对标准输入/标准输出有一些保护,你当然不能从标准输出 fprintf 到标准输入或 fgets.

Is there an explanation for this? I always thought there was some protection on stdin/stdout and you certainly can't fprintf to stdin or fgets from stdout.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    char message[20];
    read(STDOUT_FILENO, message, 20);
    write(STDIN_FILENO, message, 20);

    return 0;
}

推荐答案

尝试写入标记为只读或反之亦然的文件将导致 writeread 返回-1,失败.在这种特定情况下,stdin 和 stdout 实际上是同一个文件.本质上,在您的程序执行之前(如果您不进行任何重定向),shell 会运行:

Attempting to write on a file marked readonly or vice-versa would cause write and read to return -1, and fail. In this specific case, stdin and stdout are actually the same file. In essence, before your program executes (if you don't do any redirection) the shell goes:

  if(!fork()){
       <close all fd's>
       int fd = open("/dev/tty1", O_RDWR);
       dup(fd);
       dup(fd);
       execvp("name", argv);
  }

因此,stdin、out 和 err 都是同一个文件描述符的副本,打开用于读取和写入.

So, stdin, out, and err are all duplicates of the same file descriptor, opened for reading and writing.

这篇关于写入标准输入和读取标准输出(UNIX/LINUX/C 编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆