Recent

Author Topic: [SOLVED] Problem running external program under Linux  (Read 13202 times)

MarkMLl

  • Hero Member
  • *****
  • Posts: 6646
Re: Problem running external program under Linux
« Reply #15 on: July 29, 2021, 05:02:23 pm »
Thanks for your code, but is all that really necessary just for executing a program in console mode from a GUI application?  :o

No, but if you want it simplified I'd like cash up front please.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: Problem running external program under Linux
« Reply #16 on: July 29, 2021, 06:29:49 pm »
День добрый!
Извиняюсь, но я бы посоветовал, в таких ситуациях использовать либо чисто консольное приложение, либо LCL с использованием стандартных методов.
Это не лучший подход, для подобных решений.
Используя один или другой метод по отдельности, вы изначально сокращаете возможность сбоя программы в разных операционных системах.

Google translate:
Good afternoon!
Sorry, but I would advise, in such situations, use either a purely console application or LCL using standard methods.
This is not the best approach for such solutions.
By using one method or the other separately, you initially reduce the likelihood of a program crashing on different operating systems. :)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #17 on: July 29, 2021, 08:01:42 pm »
Hey Maurobio,

I think you're getting stuck on what could be called a difference of philosophy.

Let's see if I can't explain myself...

Linux, from the get go, has been planned to run binaries, no matter from where they originate. This means that they will always run,no matter if they have been initiated from a shell, or a GUI application.

Windows, from the get go, has been designed to ALWAYS have a GUI involved. Hence the fact that even cmd.exe MUST spawn a visual window in which then it runs what was asked of it.

To be honest, in my opinion, the outsider here is Windows, It's insistence that everything should have a window shown(Yes big irony it's called Windows for a reason, LOL) is a bit nonsensical.
But that's just my opinion and it won't solve your problem, so back to your problem...

So let's try and make things the same for each OS, and by that I mean, let's ask both to run our count inside their respective visual command line hosts:
  • For Windows we'll ask cmd.exe to run our command
  • For Linux we will use the function DetectXTerm to give us what is the system's visual command line host
    • This usually defaults to the gnome-terminal for GNOME based systems
    • Or it defaults to konsole on a KDE based system

If a system is well configured, it should have a wrapper for the default Terminal app.
What DetectXTerm should return is either that wrapper or the actual Terminal app itself.
Looking at the source of DetectXTerm you can see that both gnome-terminal and konsole are there and some of the older Terminal apps are also listed.

That wrapper, under modern Linux is usually x-terminal-emulator.
This is usually a symlink to a shell script that will eventually call the intended Terminal app.

On my Ubuntu 21.04 64b this is where it all resides:
Code: Bash  [Select][+][-]
  1. $ whereis x-terminal-emulator
  2. x-terminal-emulator: /usr/bin/x-terminal-emulator
Code: Bash  [Select][+][-]
  1. $ ll /usr/bin/x-terminal-emulator
  2. lrwxrwxrwx 1 root root 37 Aug 17  2017 /usr/bin/x-terminal-emulator -> /etc/alternatives/x-terminal-emulator*
Code: Bash  [Select][+][-]
  1. $ ll /etc/alternatives/x-terminal-emulator
  2. lrwxrwxrwx 1 root root 31 Aug 17  2017 /etc/alternatives/x-terminal-emulator -> /usr/bin/gnome-terminal.wrapper

That last file is the shell script that eventually calls the GNOME Terminal app and while looking at it's source I found out that you need to use the param "-e" to pass the program you want the Terminal to run.

With that in mind, why don't you try this:
Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button2Click(Sender: TObject);
  2. var
  3.   ShellProg, CmdLine, Datafile: string;
  4. begin
  5.   {$IFDEF WINDOWS}
  6.   ShellProg:= 'cmd.exe';
  7.   CmdLine:= ExtractFilePath(Application.ExeName)+'counter.exe';
  8.   {$ELSE}
  9.   ShellProg:= DetectXTerm;
  10.   CmdLine := ExtractFilePath(Application.ExeName)+'counter';
  11.   {$ENDIF}
  12.   Datafile := {ExtractFilePath(Application.ExeName)+}'lines.txt'; // Not sure it needs full path, so I'm leaving the comment in
  13.   AProcess := TProcess.Create(nil);
  14.   try
  15.     AProcess.Executable := ShellProg;
  16.     {$IFDEF WINDOWS}
  17.     AProcess.Parameters.Add('/c');
  18.     {$ELSE}
  19.     AProcess.Parameters.Add('-e');
  20.     {$ENDIF}
  21.     AProcess.Parameters.Add(CmdLine);
  22.     AProcess.Parameters.Add(Datafile);
  23.     AProcess.Options := AProcess.Options + [poWaitOnExit];
  24.     AProcess.Execute;
  25.     if AProcess.ExitCode <> 0 then
  26.       ShowMessageFmt('Error: %s reports error code %d', [CmdLine, AProcess.ExitCode]);
  27.   finally
  28.     AProcess.Free;
  29.   end;
  30. end;
  31.  

It works on my Ubuntu 21.04 64b and I was also able to make it work under wine doing a dir, cuz I don't have a C cross-compiler to Windows, only a FPC one.

Please adjust accordingly to your LUbuntu.

Hope this helps!!

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

maurobio

  • Hero Member
  • *****
  • Posts: 623
  • Ecology is everything.
    • GitHub
Re: Problem running external program under Linux
« Reply #18 on: July 29, 2021, 09:27:36 pm »
Hi, Gus!

Thanks a lot for your comprehensive explanation of these differences between MS-Windows and Linux.

Your code almost work. I say "almost" because, at least under MS-Windows (I have not yet tested it under Linux), it fails in two situations:

  • if the program to be executed (counter.exe) is in a path other than that of the application executable;
  • if the full path name of the data file is included with the name of that file

Both situations pose potentially serious problems for my application, since the 'external' program my users will be executing is a third-part application which should be installed separately, in its own path.

I will now proceed to perform tests under Linux Ubuntu and will report the results soon.

With best wishes,
UCSD Pascal / Burroughs 6700 / Master Control Program
Delphi 7.0 Personal Edition
Lazarus 2.0.12 - FPC 3.2.0 on GNU/Linux Mint 19.1, Lubuntu 18.04, Windows XP SP3, Windows 7 Professional, Windows 10 Home

MarkMLl

  • Hero Member
  • *****
  • Posts: 6646
Re: Problem running external program under Linux
« Reply #19 on: July 29, 2021, 10:31:09 pm »
Windows, from the get go, has been designed to ALWAYS have a GUI involved. Hence the fact that even cmd.exe MUST spawn a visual window in which then it runs what was asked of it.

Is that /really/ true? Because I've got things like tar.exe which run entirely happily in the context of am existing cmd.exe session.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

maurobio

  • Hero Member
  • *****
  • Posts: 623
  • Ecology is everything.
    • GitHub
Re: Problem running external program under Linux
« Reply #20 on: July 29, 2021, 10:37:56 pm »
Dear ALL,

Based upon the suggestions by @lucamar and @Gus, I finally settled at the following 'hybrid' code, which works as expected in both Linux and MS-Windows:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button2Click(Sender: TObject);
  2. var
  3.   {$IFDEF LINUX}ShellProg,{$ENDIF} CmdLine, Datafile: string;
  4. begin
  5.   {$IFDEF WINDOWS}
  6.   CmdLine := ExtractFilePath(Application.ExeName) + 'counter.exe';
  7.   {$ELSE}
  8.   ShellProg := DetectXTerm;
  9.   CmdLine := ExtractFilePath(Application.ExeName) + 'counter';
  10.   {$ENDIF}
  11.   Datafile := ExtractFilePath(Application.ExeName) + 'lines.txt';
  12.   AProcess := TProcess.Create(nil);
  13.   try
  14.     {$IFDEF LINUX}
  15.     AProcess.Executable := ShellProg;
  16.     AProcess.Parameters.Add('-e');
  17.     AProcess.Parameters.Add(CmdLine);
  18.     {$ENDIF}
  19.     {$IFDEF WINDOWS}
  20.     AProcess.Executable := CmdLine;
  21.     {$ENDIF}
  22.     AProcess.Parameters.Add(Datafile);
  23.     AProcess.Options := AProcess.Options + [poWaitOnExit];
  24.     AProcess.Execute;
  25.     if AProcess.ExitCode <> 0 then
  26.       ShowMessageFmt('Error: %s reports error code %d', [CmdLine, AProcess.ExitCode]);
  27.   finally
  28.     AProcess.Free;
  29.   end;
  30. end;

Executing a separate "shell program" under MS-Windows is not necessary and gave rise to many problems, therefore under this OS the command line can be executed directly (as per the code above).

I have not yet tested this code with my 'real' application, but in principle I can see no reason why it should not work (BTW, how many times have such words been proffered before catastrophic system failures?  ::))

Thank you very much!

With best wishes,
UCSD Pascal / Burroughs 6700 / Master Control Program
Delphi 7.0 Personal Edition
Lazarus 2.0.12 - FPC 3.2.0 on GNU/Linux Mint 19.1, Lubuntu 18.04, Windows XP SP3, Windows 7 Professional, Windows 10 Home

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #21 on: July 29, 2021, 10:46:01 pm »
Hey Maurobio,

Thanks a lot for your comprehensive explanation of these differences between MS-Windows and Linux.

No problem at all. I thought that this thread was going a bit sideways and it needed a bit more words to get it on track, so I put some words down ;)

Your code almost work. I say "almost" because, at least under MS-Windows (I have not yet tested it under Linux), it fails in two situations:

  • if the program to be executed (counter.exe) is in a path other than that of the application executable;
  • if the full path name of the data file is included with the name of that file

Both situations pose potentially serious problems for my application, since the 'external' program my users will be executing is a third-part application which should be installed separately, in its own path.

I will now proceed to perform tests under Linux Ubuntu and will report the results soon.

With best wishes,

While testing under Ubuntu, not wine, I tested these two cases and they all worked:
  • /full/path/to/counter /full/path/to/lines.txt
  • /full/path/to/counter lines.txt

I don't remember if I tested counter lines.txt, since the executable and the text file is under the same folder as the calling binary, but that's not what worries you since the counter binary will be somewhere else in the system.

The code I provided you is using FULL path to counter binary and, if you uncomment that piece of code, you can enable the text file to be used with FULL path and it all works.

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #22 on: July 29, 2021, 10:49:57 pm »
Hey Mark,

Is that /really/ true? Because I've got things like tar.exe which run entirely happily in the context of am existing cmd.exe session.

Well, once the cmd.exe window is shown, it can then run any amount of commands you give it.
But this doesn't invalidate the fact that you're still looking at a Window that host's the cmd.exe, right? And to be able to run that first command, the window HAS to pop up...
On Linux, the host system(Terminal app) is optional, right?

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

MarkMLl

  • Hero Member
  • *****
  • Posts: 6646
Re: Problem running external program under Linux
« Reply #23 on: July 29, 2021, 10:53:33 pm »
Well, once the cmd.exe window is shown, it can then run any amount of commands you give it.
But this doesn't invalidate the fact that you're still looking at a Window that host's the cmd.exe, right? And to be able to run that first command, the window HAS to pop up...
On Linux, the host system(Terminal app) is optional, right?

I'm afraid that I read your "even cmd.exe MUST spawn a visual window in which then it runs what was asked of it." as implying that cmd.exe always created an additional window for a program. My apologies if I misinterpreted you.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #24 on: July 29, 2021, 10:57:07 pm »
Hey Maurobio,

Based upon the suggestions by @lucamar and @Gus, I finally settled at the following 'hybrid' code, which works as expected in both Linux and MS-Windows:

YAY, I'm glad you were finally able to get it working !!!

Executing a separate "shell program" under MS-Windows is not necessary and gave rise to many problems, therefore under this OS the command line can be executed directly (as per the code above).

Hummm, sorry for causing you grief with running another cmd unnecessarily!!
My intention was to make a parallel between the 2 OSs, not mess up your life and for that I apologize!!

I have not yet tested this code with my 'real' application, but in principle I can see no reason why it should not work (BTW, how many times have such words been proffered before catastrophic system failures?  ::))

LOL!!  :D

Thank you very much!

You are more than welcome!!!

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #25 on: July 29, 2021, 10:59:05 pm »
Hey Mark,

I'm afraid that I read your "even cmd.exe MUST spawn a visual window in which then it runs what was asked of it." as implying that cmd.exe always created an additional window for a program. My apologies if I misinterpreted you.

No need for apologies Mark!!

I've made my fair share of bad assumptions to know where you're coming from :)

All's good :)

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

maurobio

  • Hero Member
  • *****
  • Posts: 623
  • Ecology is everything.
    • GitHub
Re: Problem running external program under Linux
« Reply #26 on: July 29, 2021, 10:59:31 pm »
Dear ALL,

Your are such gentlemen! It is a honour and a privilege to be able to receive your help!

Thanks a lot for your time and patience.

With best wishes,
UCSD Pascal / Burroughs 6700 / Master Control Program
Delphi 7.0 Personal Edition
Lazarus 2.0.12 - FPC 3.2.0 on GNU/Linux Mint 19.1, Lubuntu 18.04, Windows XP SP3, Windows 7 Professional, Windows 10 Home

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1088
  • Professional amateur ;-P
Re: Problem running external program under Linux
« Reply #27 on: July 29, 2021, 11:05:37 pm »
Hey Maurobio,

Your are such gentlemen! It is a honour and a privilege to be able to receive your help!

AAAwww, stop it, now you're making me all red in the face  :-[ ;)

Thanks a lot for your time and patience.

You're quite welcome. The pleasure was all mine :)

Cheers,
Gus
Lazarus 3.99(main) FPC 3.3.1(main) Ubuntu 23.10 64b Dark Theme
Lazarus 3.0.0(stable) FPC 3.2.2(stable) Ubuntu 23.10 64b Dark Theme
http://github.com/gcarreno

maurobio

  • Hero Member
  • *****
  • Posts: 623
  • Ecology is everything.
    • GitHub
Re: Problem running external program under Linux
« Reply #28 on: July 30, 2021, 12:52:14 am »
Dear ALL,

BTW, the code provided by @Gus, with my humble adaptations, just worked fine with my 'real' application! :D

Again, thank you very much.

With best wishes,
UCSD Pascal / Burroughs 6700 / Master Control Program
Delphi 7.0 Personal Edition
Lazarus 2.0.12 - FPC 3.2.0 on GNU/Linux Mint 19.1, Lubuntu 18.04, Windows XP SP3, Windows 7 Professional, Windows 10 Home

PascalDragon

  • Hero Member
  • *****
  • Posts: 5444
  • Compiler Developer
Re: Problem running external program under Linux
« Reply #29 on: July 30, 2021, 09:02:29 am »
Windows, from the get go, has been designed to ALWAYS have a GUI involved. Hence the fact that even cmd.exe MUST spawn a visual window in which then it runs what was asked of it.

This is not quite correct. Windows evolved from DOS where the only possibility were console applications.

The header of PE/COFF files contains a field that decides the subsystem of the executable (in this case GUI vs. CUI, there are also other values that are not important for this). Applications that have the subsystem type CUI require a terminal, but not a console window, cause it's perfectly fine to execute console applications in e.g. a SSH session (when you connect to a Windows using SSH) or e.g. on the Windows IoT core variant of devices where you have either WinRT style apps or console applications. (Also when starting a process it can be requested to hide that window upon start)

TL;DR: If you start a CUI application from a process that does not have a terminal associated then Windows will automatically spawn a console window, but if a terminal is associated it will continue to use that.

 

TinyPortal © 2005-2018