MD XF MD XF - 1 month ago 16
C Question

Check if program is being piped

I'm writing a program that speeds up the

git push
operation. Here's what it needs to do:

printf("[github-username]\n[github-password]");


I'd then use it like so:

git-autologin | git push


But I don't want there to be any chance of someone simply typing
git-autologin
or
git-autologin > file.txt
and being able to see my username and password. I know it sounds silly 'cause anyone can still automate the git commands but it's unlikely that any untrusted user will ever get on my system.

My question: How could I tell if standard output is writing to a file/terminal or if it's being piped?

Edit: Is there any way to determine the PID or more information about the process it's being piped to?

Answer

You can detect when stdout is a terminal by using (on Linux & POSIX!) the isatty(3) function, probably as isatty(STDOUT_FILENO)

So you could guess that if isatty(STDOUT_FILENO) is false, the standard output is would be redirected or piped.

Alternatively, use fstat(2) as fstat(STDOUT_FILENO, &stdoutstat);

But you should set up ssh correctly (with credentials, STFW for any SSH tutorial!) on your system, to avoid having git asking any password.

Comments