http://www.perlmonks.org?node_id=542850

slloyd has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to tell if a program was run from a command prompt (Windows)? The user could double-click on the program from an explorer window or they might open up a command prompt and run the program from the command prompt. I want to be able to detect how the program was launched. Any ideas?

-------------------------------
Perl - Regularly Expression yourlself
http://www.basgetti.com

  • Comment on Determining if a program was run from a command prompt.

Replies are listed 'Best First'.
Re: Determining if a program was run from a command prompt.
by Albannach (Monsignor) on Apr 12, 2006 at 15:10 UTC
    While it's not totally foolproof (note the follow-ups), this works for me.

    --
    I'd like to be able to assign to an luser

Re: Determining if a program was run from a command prompt.
by BrowserUk (Patriarch) on Apr 12, 2006 at 15:51 UTC

    How sure do you want to be and how much work are you prepared for to get the information?

    There is no (officially) documented way of obtaining information about the parent process, but there is a fairly well known undocumented method of obtaining the ppid. It means getting your fingers dirty with Win32::API or XS code.

    The starting point is the semi-documented, could-change-any-moment API ZwQueryInformationProcess, and the undocumented PVOID Reserved3 member of the PROCESS_BASIC_INFORMATION structure, which is the parent process id. There are various ways of getting the name/path once you have that.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Determining if a program was run from a command prompt.
by demerphq (Chancellor) on Apr 12, 2006 at 16:11 UTC

    UPDATE: Bah. This doesnt work. Never mind me. For some reason when you click on the script it gets executed from a console, so the -t tests says true. Wheras if i launch a script from my editor it shows false, so I assumed the same would be true when double-clicking. I shouldnt have assumed..... :-(

    Sure, use the -t filetest operation to test if STDIN is connected to a TTY. Try the following script (you might have to change where the log gets written to.)

    #!perl -l open my $log,">>C:/tmp/log.log" or die $!; my $term_type=-t STDIN ? "Terminal" : "Non Terminal"; print $log localtime(time)." $term_type"; print localtime(time)." $term_type";
    ---
    $world=~s/war/peace/g