Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Write() to stdin works??

380 views
Skip to first unread message

ishwar...@gmail.com

unread,
Apr 23, 2013, 12:46:32 PM4/23/13
to
System is Linux with gcc version 4.7.1 (Debian 4.7.1-2) and
the following code writes to stdin.

#include <stdio.h>
#include <unistd.h>

int main()
{
if (write(0, "Hello world!\n", 13) != 13)
fprintf(stderr, "Write failed\n");
return 0;
}

Any pointers will be appreciated.
-ishwar

Rainer Weikusat

unread,
Apr 23, 2013, 12:51:40 PM4/23/13
to
ishwar...@gmail.com writes:
> System is Linux with gcc version 4.7.1 (Debian 4.7.1-2) and
> the following code writes to stdin.
>
> #include <stdio.h>
> #include <unistd.h>
>
> int main()
> {
> if (write(0, "Hello world!\n", 13) != 13)
> fprintf(stderr, "Write failed\n");
> return 0;
> }

If you execute this interactively, it writes to a file descriptor
associated with 'the terminal'. Since you can write to that, it isn't
surprising that trying to do so succeeds.

Richard Kettlewell

unread,
Apr 23, 2013, 12:53:55 PM4/23/13
to
ishwar...@gmail.com writes:
> System is Linux with gcc version 4.7.1 (Debian 4.7.1-2) and
> the following code writes to stdin.
>
> #include <stdio.h>
> #include <unistd.h>
>
> int main()
> {
> if (write(0, "Hello world!\n", 13) != 13)
> fprintf(stderr, "Write failed\n");
> return 0;
> }

It’ll succeed if fd 0 is writable. That’s likely to be the case if you
run it from a shell without redirection, since fd 0 will be the
terminal.

It’ll fail if fd 0 is closed or is not writable, for instance if you’ve
redirected it from a file.

--
http://www.greenend.org.uk/rjk/

Barry Margolin

unread,
Apr 23, 2013, 2:26:07 PM4/23/13
to
In article <aacdd56c-0cfd-4967...@googlegroups.com>,
When you login, the system does something similar to to:

fd = open("/dev/tty", O_RW);
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);

So all those descriptors are actually referring to the same stream, and
it's open in read-write mode. So there's no error.

--
Barry Margolin, bar...@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
0 new messages