如何确定我的进程是否以交互方式运行?

时间:2022-11-26 07:13:39

Is there a standard(ish) POSIX way of determining if my process (I’m writing this as a Ruby script right now; but I’m curious for multiple environments, including Node.js and ISO C command-line applications) is being run in an interactive terminal, as opposed to, say, cron, or execution from another tool, or… so on and so forth.

是否有一种标准的(ish)POSIX方式来确定我的进程(我现在正在将其写为Ruby脚本;但我对包括Node.js和ISO C命令行应用程序在内的多个环境感到好奇)正在在交互式终端中运行,而不是像cron,或从其他工具执行,或......等等。

Specifically, I need to acquire user input in certain situations, and I need to fail fatally if that is determinably not possible (i.e. being run by cron.) I can do this with an environment variable, but I’d prefer something more standard-ish, if I can.

具体来说,我需要在某些情况下获取用户输入,如果确定不可能(即由cron运行),我需要致命地失败。我可以使用环境变量做到这一点,但我更喜欢更标准的东西 - 是的,如果可以的话。

3 个解决方案

#1


15  

I've always used $stdout.isatty to check for this. Other approaches might include checking the value of ENV['TERM'] or utilizing the ruby-terminfo gem.

我总是使用$ stdout.isatty来检查这个。其他方法可能包括检查ENV ['TERM']的值或使用ruby-terminfo gem。

#2


4  

The closest you'll get, AFAIK, is isatty(). But as the page itself says, nothing guarantees that a human is controlling the terminal.

你得到的最接近的AFAIK是isatty()。但正如页面本身所说,没有什么可以保证人类正在控制终端。

#3


0  

As @Mitch wrote it in a comment, which can also be useful to some people:

正如@Mitch在评论中写的那样,对某些人也有用:

For anyone who came here looking for windows, try System.Environment.UserInteractive for .Net or GetUserObjectInformation for win32, which will fail for non-interactive processes

对于那些来这里寻找窗口的人来说,尝试使用.Net的System.Environment.UserInteractive或win32的GetUserObjectInformation,这对于非交互式进程会失败

#1


15  

I've always used $stdout.isatty to check for this. Other approaches might include checking the value of ENV['TERM'] or utilizing the ruby-terminfo gem.

我总是使用$ stdout.isatty来检查这个。其他方法可能包括检查ENV ['TERM']的值或使用ruby-terminfo gem。

#2


4  

The closest you'll get, AFAIK, is isatty(). But as the page itself says, nothing guarantees that a human is controlling the terminal.

你得到的最接近的AFAIK是isatty()。但正如页面本身所说,没有什么可以保证人类正在控制终端。

#3


0  

As @Mitch wrote it in a comment, which can also be useful to some people:

正如@Mitch在评论中写的那样,对某些人也有用:

For anyone who came here looking for windows, try System.Environment.UserInteractive for .Net or GetUserObjectInformation for win32, which will fail for non-interactive processes

对于那些来这里寻找窗口的人来说,尝试使用.Net的System.Environment.UserInteractive或win32的GetUserObjectInformation,这对于非交互式进程会失败