0

In another question I asked I realized I want to redirect stdin but have it provide absolutely no input. For example, I want a call to getchar() to hang forever. I would then like to terminate the application by sending a kill signal.

I tried freopen("/dev/null", "r", stdin); but this does not work because /dev/null when read returns an EOF which it seems triggers the getchar() to be executed, and my program is exited.

How can I redirect stdin to not read from anything at all?

Community
  • 1
  • 1
boltup_im_coding
  • 6,345
  • 6
  • 40
  • 52
  • End of file is a pseudocharacter in the Linux/C world, typically with the value -1. If you want to wait until killed, reading from stdin is not the way to do it. Edit your question, or submit another. – keshlam Feb 04 '14 at 19:45

1 Answers1

2

On linux, you could try to create a named pipe: http://linux.die.net/man/3/mkfifo and just read from it.

But what are you trying to ultimately achieve? It seems there must be a better way.

Jakub Kotowski
  • 7,411
  • 29
  • 38
  • I like this approach. I tried `mkfifo("empty_input", S_IRUSR| S_IWUSR);` and then `freopen("./empty_input", "w", stdin);`. I am assuming this would work, but my `mkfifo` call returns `-1` and sets `errono` to `EACCES` which is "permission denied" – boltup_im_coding Feb 04 '14 at 21:16
  • I tried it and for me it executes without error and it just hangs on `open("./empty_input", O_WRONLY|O_CREAT|O_TRUNC, 0666` (output of strace). – Jakub Kotowski Feb 04 '14 at 21:36
  • I tried running `mkfifo empty_input` from the command line and seems that the command is not found on my OS. This is an embedded Linux kernel. – boltup_im_coding Feb 05 '14 at 00:32
  • Yea, it seems that mkfifo is not implemented in some OSs (MacOS, ...). Which embedded system do you have? I am not sure if it changes anything but you can try using mknod instead: `mknod("empty_input", S_IFIFO|0600, 0);` http://man7.org/linux/man-pages/man2/mknod.2.html That the `mkfifo` _command_ is not present doesn't necessarily mean anything, IMO. – Jakub Kotowski Feb 05 '14 at 09:16
  • I am so close - I have this working. But `getchar()` seems to return if I write nothing (because of EOF) or a character if I do write something but do not put a newline char (`\n`). What should I write to the FIFO that a call to `getchar()` will hang on? – boltup_im_coding Feb 05 '14 at 20:34
  • No problem, what's the workaround then? :) Btw, for me it hanged when I just tried to open the FIFO, I didn't have to do anything else. – Jakub Kotowski Feb 05 '14 at 20:41
  • 1
    I edited the other application to see if when it reads from `stdin` if its equal to a special character. If it is, then I `sleep()` in that app. – boltup_im_coding Feb 05 '14 at 23:50