1

I am writing two c files that one is to write(by stdout) and another is read(by stdin).

But the read code is always hangs with read(), I have tried fread function but useless.

Can someone give advice?

Write example:

int main() {
    char *a_string="Hello";
    write(fileno(stdout), a_string, strlen(a_string)+1);

    return 0; 
}

Read example:

int main() {
    char buffer[100];
    read(fileno(stdin), buffer, 100-1);
    printf("buffer=%s\n", buffer);

    return 0;
}
黃思綸
  • 65
  • 2
  • 9
  • Take a look at [fgets](https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm) – LPs Nov 07 '16 at 08:03
  • Normally your code will hang until you hit the Enter key. And furthermore your string won't be zero terminated. Use rather `fgets` for reading, and `fputs` for writing. – Jabberwocky Nov 07 '16 at 08:08
  • Due to some reason, I want to use read() and write() only. – 黃思綸 Nov 07 '16 at 08:11
  • Hi @usr Its works, can I run these codes separately? – 黃思綸 Nov 07 '16 at 08:14
  • 1
    What is that _some reason_ you want to use `read` and `write`? What are you _actually_ trying to do ? Please read this : [XY problem](http://xyproblem.info/). And read this: [How to ask](http://stackoverflow.com/help/how-to-ask) – Jabberwocky Nov 07 '16 at 08:16
  • 1
    @黃思綸 You can't run them separately if you want them to communicate. If you don't want to use pipe then you'll have to use one of the [IPCs](https://en.wikipedia.org/wiki/Inter-process_communication). – P.P Nov 07 '16 at 08:17
  • I assume a POSIX or Linux operating system. Then read http://advancedlinuxprogramming.com/ ; perhaps you need a multiplexing call like [poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html) – Basile Starynkevitch Nov 07 '16 at 08:20
  • I am studying two pipe codes that communicates to each other by read(stdin) and write(stdout). That's really amazing. – 黃思綸 Nov 07 '16 at 08:26

2 Answers2

0

You need to input the EOF to stop, in Linux,it's Ctrl+D.

Jinhua Fan
  • 21
  • 5
  • In linux, stdin and stdout are unnamed pipes. When you close all write descriptor for a pipe, it sends EOF to a read descriptor of this pipe. – nopasara Nov 07 '16 at 09:14
  • @nopasara I don't see how this is particularly relevant. – MD XF Nov 07 '16 at 09:17
  • @MD XF maybe not, i though he was piping two programs together. What for the first writing program exampled? – nopasara Nov 07 '16 at 09:39
  • 1
    This is a signal you manually input, and when read() encounter this signal, it's return. – Jinhua Fan Nov 07 '16 at 09:41
0

The read code is always hangs with read(), I have tried fread function but useless.

This is because read and fread, unlike fgets and similar functions, do not quit reading when the user inputs a newline (presses Enter). It waits until EOF is read or until the specified bytes have been read.

To send EOF to read you must press Ctrl+D.

MD XF
  • 7,860
  • 7
  • 40
  • 71