写入标准输入和标准输出从阅读(UNIX / LINUX / C编程) [英] Writing to stdin and reading from stdout (UNIX/LINUX/C Programming)
问题描述
我工作的分配,其中一个程序拿了一个文件描述符作为参数(一般是在exec调用父),并从文件中读取和写入文件的描述符,并在我的测试中,我意识到,计划将在命令行工作,如果我用0,1或2作为文件描述符没有给出一个错误。这是有道理的,我只是说我会写信给标准输入,并将它显示在屏幕上。
对此有一个解释?我一直以为有在标准输入/输出一些保护,你当然不能向fprintf中或标准输入从与fgets标准输出。
的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;
诠释的main()
{
字符信息[20];
读(STDOUT_FILENO,消息,20);
写(STDIN_FILENO,消息,20); 返回0;
}
试图对标记为只读,反之亦然会引起文件的写写
和读
返回-1,并失败。在这种的具体的情况下,stdin和stdout实际上是相同的文件。从本质上讲,你的程序执行前(如果你没有做任何重定向)外壳有云:
如果(!叉()){
<关闭所有FD的>
INT FD =打开(的/ dev / tty1上,O_RDWR);
DUP(FD);
DUP(FD);
execvp(名,argv的);
}
所以,标准输入,输出和ERR在同一文件描述符的所有副本,打开阅读和写作。
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.
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;
}
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);
}
So, stdin, out, and err are all duplicates of the same file descriptor, opened for reading and writing.
这篇关于写入标准输入和标准输出从阅读(UNIX / LINUX / C编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!