April 24, 2024, 04:06:13 AM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


HowTo: Create and run a detached process

Started by Ionic Wind Support Team, August 07, 2008, 01:28:34 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Ionic Wind Support Team

Hello,
Just some info Emergence Linux programmers need it they want to create and launch a detached process.  While you can use the SYSTEM command it will wait for the process to finish before returning, sometimes you need to launch another program and not have anything else to do with it.

Here is some Emergence code to do it:


declare cdecl extern fork(),int
declare cdecl extern execlp(command as string,...)
declare cdecl extern oswait alias "wait"()

Sub RunCommand(string command,int target)
int pid
if target = 0
pid = fork()
if pid = -1
messagebox 0,"Unable to fork","Error"
return
endif
if pid = 0
pid = fork()
if pid
end
else
execlp("gnome-terminal","gnome-terminal","-x",command,0)
endif
endif
oswait()
else
if target = 1
pid = fork()
if pid = -1
messagebox 0,"Unable to fork","Error"
return
endif
if pid = 0
pid = fork()
if pid
end
else
execlp(command,command,0)
endif
endif
oswait()
endif
endif
return
Endsub


Target is either 0 for a terminal app or 1 for a gnome/gtk/kde/whatever application.

This method is known as the double fork, and allows one process to launch another without creating a zombie when the launched process ends.  You can replace "gnome-terminal" with whatever shell you prefer, just be sure to use the correct switch setting.

fork() is how Linux works.  Simply put fork() creates an identical image of the running process, execution in both the original and forked process continues at the same point after the fork() function.  The pid, or process ID, will be one of:

0 - This is the child process
-1 - The fork failed
Any other number - This is the parent process.

execlp replaces the running process with the one specified in the first parameter.  So when PID = 0 the second child is replaced with the specified executable and ran, the first child ends, and the parent uses oswait, an alias for the Linux kernel wait function, to wait for the first child to die. 

If you want to know more about double forking then search google.  It takes a bit to get your head around the three processes, but once you understand it, it is a powerful tool.

Later,
Paul.
Ionic Wind Support Team