简体   繁体   中英

Linux terminal pipe to my C++ program

I'm not sure about the terminology, and when I googled this I got many misleading results. I just need a push and I'll be fine.

How can put my program as a target to piping in linux terminal?

Say I wrote a C++ program MyProg

I would like to be able to do something like

$ ls | ./MyProg

Could you please give me a hint to what function/stream can be used for this?

Piping, as you call it, is nothing special in Linux, that's why you do not find it.

What the pipe does is to redirect the standard output ( stdout ) of one program to the standard input ( stdin ) of another. So simply read the standard input, and you will find the text there. You an use std::cin if you want to go the C++ way, or *scanf() in C mode.

If you want to know if stdin refers to the actual terminal or some redirection, you can use isatty(0) (0 is the fd of stdin, there is a constant somewhere but I can't remember the name, while everybody know that stdin is 0).

You should handle standard input (stdin) , output (stdout) and error (stderr) in your application. They have reserved file descriptor numbers. Please refer to following link File descriptor Wiki

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM