Fork: Difference between revisions

23,011 bytes added ,  5 months ago
m
m (→‎REXX version 1 using REPLY: remove returned value and let subroutine go on after the program's end)
m (→‎{{header|Wren}}: Minor tidy)
 
(43 intermediate revisions by 30 users not shown)
Line 1:
{{task|Programming environment operations}}In this task, the goal is to spawn a new [[process]] which can run simultaneously with, and independently of, the original parent process.
 
;Task:
 
Spawn a new [[process]] which can run simultaneously with, and independently of, the original parent process.
<br><br>
 
=={{header|Ada}}==
{{libheader|POSIX}}
<langsyntaxhighlight lang="ada">with Ada.Text_IO,
POSIX.Process_Identification,
POSIX.Unsafe_Process_Primitives;
Line 20 ⟶ 25:
when others =>
Put_Line ("Something went wrong.");
end Fork;</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">
var pid = fork()
switch (pid) {
Line 36 ⟶ 41:
break
}
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
Line 42 ⟶ 47:
 
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9 - "fork" is not part of the standard's prelude.}}
<langsyntaxhighlight lang="algol68">main:
(
INT pid;
Line 52 ⟶ 57:
print("ERROR: Something went wrong")
FI
)</langsyntaxhighlight>
Output:
<pre>
Line 58 ⟶ 63:
This is the original process
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">MsgBox, 4, Fork, Start another process?
IfMsgBox, Yes
Run, %A_AhkPath% "%A_ScriptFullPath%"
MsgBox, 0, Fork, Stop this process.</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">' Fork
pid = FORK
IF pid = 0 THEN
PRINT "I am the child, my PID is:", MYPID
ENDFORK
ELIF pid > 0 THEN
PRINT "I am the parent, pid of child:", pid
REPEAT
PRINT "Waiting for child to exit"
SLEEP 50
UNTIL REAP(pid)
ELSE
PRINT "Error in fork"
ENDIF</syntaxhighlight>
 
{{out}}
<pre>prompt$ bacon fork.bac
Converting 'fork.bac'... done, 14 lines were processed in 0.004 seconds.
Compiling 'fork.bac'... cc -c fork.bac.c
cc -o fork fork.bac.o -lbacon -lm
Done, program 'fork' ready.
prompt$ ./fork
I am the parent, pid of child:12733
Waiting for child to exit
I am the child, my PID is:12733</pre>
 
==={{header|FreeBASIC}}===
In Windows without using windows.bi, we can use a vbscript command.
<syntaxhighlight lang="freebasic">
Function script(s As String) As String
Dim As String g = _
"Set WshShell = WScript.CreateObject(""WScript.Shell"")" + _
Chr(13,10) + "Return = WshShell.Run("""+s+" "",1,0)"
Return g
End Function
 
Function guardaArchivo(nombreArchivo As String, p As String) As String
Dim As Long n = Freefile
If Open (nombreArchivo For Binary Access Write As #n) = 0 Then
Put #n,,p
Close
Else
Print "No se puede guardar " + nombreArchivo : Sleep : End
End If
Return nombreArchivo
End Function
 
Sub ejecutaScript(nombreArchivo As String)
Shell "cscript.exe /Nologo " + nombreArchivo
End Sub
 
Var g = script("notepad.exe") '<< ejecuta este .exe (notepad como demo)
guardaArchivo("script.vbs",g)
ejecutaScript("script.vbs")
Dim As String s
Print "Hola"
Input "Teclee algo: ", s
Print s
Kill "script.vbs"
Sleep
</syntaxhighlight>
 
==={{header|Run BASIC}}===
You can run a program until that program executes a wait statement.
Once the program waits,you can use it's functions.
<syntaxhighlight lang="runbasic">run "someProgram.bas",#handle
render #handle ' this runs the program until it waits
' both the parent and child are running
' --------------------------------------------------------
' You can also call a function in the someProgram.bas program.
' For example if it had a DisplayBanner Funciton.
#handle DisplayBanner("Welcome!")</syntaxhighlight>
 
==={{header|Visual Basic .NET}}===
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Sub Fork()
Console.WriteLine("Spawned Thread")
End Sub
 
Sub Main()
Dim t As New System.Threading.Thread(New Threading.ThreadStart(AddressOf Fork))
t.Start()
 
Console.WriteLine("Main Thread")
t.Join()
End Sub
 
End Module</syntaxhighlight>
 
=={{header|Batch File}}==
While you cannot fork into asynchronous subroutines conventionally, there are workarounds involving the <code>start</code> command.
 
<syntaxhighlight lang="dos">
@echo off
 
if "%1" neq "" goto %1 || echo Not a valid subroutine
 
echo Starting mySubroutine1
start "" "%~n0" mySubroutine1
echo.
 
echo Starting mySubroutine2 6 3
start "" "%~n0" mySubroutine2 6 3
echo.
 
echo Starting mySubroutine3
start "" "%~n0" mySubroutine3
echo.
 
:: We wait here for the subroutines to run, but they are running asynchronously
timeout /t 1
 
for /l %%i in (1,1,3) do (
for /f "tokens=*" %%j in (output%%i.txt) do (
set output%%i=%%j
del output%%i.txt
)
)
echo.
echo.
echo Return values
echo ----------------------------
echo mySubroutine1: %output1%
echo mySubroutine2: %output2%
echo mySubroutine3: %output3%
 
pause>nul
exit
 
:mySubroutine1
echo This is the result of subroutine1 > output1.txt
exit
 
:mySubroutine2
set /a result=%2+%3
echo %result% > output2.txt
exit
 
:mySubroutine3
echo mySubroutine1 hasn't been run > output3.txt
if exist output1.txt echo mySubroutine1 has been run > output3.txt
exit
</syntaxhighlight>
 
Output:
 
<pre>
Starting mySubroutine1
 
Starting mySubroutine2 6 3
 
Starting mySubroutine3
 
 
Waiting for 0 seconds, press a key to continue ...
 
 
Return values
----------------------------
mySubroutine1: This is the result of subroutine1
mySubroutine2: 9
mySubroutine3: mySubroutine1 has been run
</pre>
 
=={{header|C}}==
{{libheader|POSIX}}<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 86 ⟶ 261:
 
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text">waiting for child 3604...
child process: done
child 3604 finished</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Threading;
 
namespace Fork {
class Program {
static void Fork() {
Console.WriteLine("Spawned Thread");
}
 
static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(Fork));
t.Start();
 
Console.WriteLine("Main Thread");
t.Join();
 
Console.ReadLine();
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
Line 94 ⟶ 291:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="cpp">#include<iostream>
#include<unistd.h>
 
Line 115 ⟶ 312:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Through its Java interop capabilities, Clojure has full access to the JRE's process creation and control facilities. The ''clojure.java.shell'' API (in Clojure 1.2; there's an equivalent in 1.1 ''clojure.contrib.shell'') uses these facilities to provide a convenient way of running a shell command in a separate process, providing its arguments, input, environment, and working dir as necessary, and capturing the process's return code and its stdout and stderr output.
<langsyntaxhighlight lang="clojure">(require '[clojure.java.shell :as shell])
(shell/sh "echo" "foo") ; evaluates to {:exit 0, :out "foo\n", :err ""}</langsyntaxhighlight>
Though this starts a separate process, the code in ''shell/sh'' blocks until the process completes. We can get other stuff done in the meantime by running the function in a separate thread with the core function ''future''. Suppose we want to find files named "needle.*" in a large directory tree ''haystack'', and do other stuff while the search proceeds. Using the Unix-like command ''find'' the code would look something like
<langsyntaxhighlight lang="clojure">(let [search (future (shell/sh "find" "." "-name" "needle.*" :dir haystack))]
(while (and (other-stuff-to-do?) (not (future-done? search)))
(do-other-stuff))
Line 128 ⟶ 325:
(if (zero? exit)
(do-something-with out)
(report-errors-in err))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Using libc fork
 
{{works with|GnuCOBOL}}
 
<syntaxhighlight lang="cobol"> identification division.
program-id. forking.
 
data division.
working-storage section.
01 pid usage binary-long.
 
procedure division.
display "attempting fork"
 
call "fork" returning pid
on exception
display "error: no fork linkage" upon syserr
end-call
 
evaluate pid
when = 0
display " child sleeps"
call "C$SLEEP" using 3
display " child task complete"
when < 0
display "error: fork result not ok" upon syserr
when > 0
display "parent waits for child..."
call "wait" using by value 0
display "parental responsibilities fulfilled"
end-evaluate
 
goback.
end program forking.</syntaxhighlight>
 
{{out}}
<pre>prompt$ cobc -xj forking.cob
attempting fork
parent waits for child...
child sleeps
child task complete
parental responsibilities fulfilled</pre>
 
=={{header|Common Lisp}}==
Line 138 ⟶ 379:
{{works with|SBCL}}
 
<langsyntaxhighlight lang="lisp">(let ((pid (sb-posix:fork)))
(cond
((zerop pid) (write-line "This is the new process."))
((plusp pid) (write-line "This is the original process."))
(t (error "Something went wrong while forking."))))</langsyntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">import core.thread;
import std.stdio;
 
void main() {
new Thread({
writeln("Spawned thread.");
}).start;
writeln("Main thread.");
}</syntaxhighlight>
 
{{out}}
<pre>Main thread.
Spawned thread.</pre>
 
=={{header|DCL}}==
In OpenVMS DCL, spawning a subprocess creates a partially independent process. The parent and child processes share certain pooled quotas, certain shared resources, and if the parent process is deleted then the child process is too automatically.
 
<syntaxhighlight lang="dcl">$! looper.com procedure
$ i = 10
$ loop:
$ show time
$ wait 'p1
$ i = i - 1
$ if i .gt. 0 then $ goto loop</syntaxhighlight>
{{out}}
<pre>$ spawn /nowait /notify @looper 0::2 ! up to 8 parameters are allowed
%DCL-S-SPAWNED, process DAVID_51258 spawned ! random number suffix assigned
$
4-JUN-2015 13:13:50
show default5 13:13:52 ! display anomaly due to parent and child overwriting output
4-JUN-2015 13:13:54
USER_ROOT:[DAVID]
$
4-JUN-2015 13:13:57
4-JUN-2015 13:13:59
Interrupt ! ctrl-c is the interrupt character; all child processes are deleted immediately
 
$
Subprocess DAVID_51258 has completed
$</pre>
To create a more independent process requires a privilege, e.g. detach. There isn't a mechanism for passing parameters to the detached process, so we embed them in a jacket procedure (possibly created dynamically).
<syntaxhighlight lang="dcl">$! fork.com procedure
$ set noverify ! detached processes have verify on by default which clutters up the output log file
$ @looper 0::2</syntaxhighlight>
{{out}}
<pre>$ run /detach sys$system:loginout /input = fork /output = fork
%RUN-S-PROC_ID, identification of created process is 23A4195C
$ stop/id=23A4195C ! rather than just waiting the 10 loop iterations
$ type fork.log
$! fork.com procedure
$ set noverify
4-JUN-2015 13:35:47
4-JUN-2015 13:35:49
4-JUN-2015 13:35:51
4-JUN-2015 13:35:53
4-JUN-2015 13:35:55
4-JUN-2015 13:35:57</pre>
=={{header|Delphi}}==
{{libheader| System.Threading}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Fork_app;
 
{$APPTYPE CONSOLE}
 
uses
System.Threading;
 
procedure Fork;
begin
Writeln('Spawned Thread');
end;
 
var
t: ITask;
 
begin
t := TTask.Run(fork);
 
Writeln('Main Thread');
 
TTask.WaitForAll(t);
Readln;
end.</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Fork do
def start do
spawn(fn -> child end)
IO.puts "This is the original process"
end
def child, do: IO.puts "This is the new process"
end
 
Fork.start</syntaxhighlight>
 
{{out}}
<pre>
This is the original process
This is the new process
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(fork).
-export([start/0]).
 
Line 153 ⟶ 498:
 
child() ->
io:format("This is the new process~n").</langsyntaxhighlight>
 
Then you can compile your code and execute it:
 
<langsyntaxhighlight lang="erlang">c(fork).
fork:start().</langsyntaxhighlight>
 
=={{header|Factor}}==
This works only in the terminal, if used from the UI the child process won't print.
 
<langsyntaxhighlight lang="factor">USING: unix unix.process ;
 
[ "Hello form child" print flush 0 _exit ] [ drop "Hi from parent" print flush ] with-fork</syntaxhighlight>
 
[ "Hello form child" print flush 0 _exit ] [ drop "Hi from parent" print flush ] with-fork</lang>
=={{header|Fexl}}==
There are many levels at which I can address this task. I'll start from the lowest possible level:
<langsyntaxhighlight lang="fexl">fork \pid
print "pid = ";print pid;nl;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 179 ⟶ 525:
 
At the next level up, we can define a "spawn" function which makes it easy to fork a child process and interact with its stdin, stdout, and stderr:
<langsyntaxhighlight lang="fexl">
# (spawn child_fn next)
# Fork the child function as a process and return its pid, stdin, stdout, and
Line 267 ⟶ 613:
)
)
</syntaxhighlight>
</lang>
 
Next, we define a test_pipe function to test the whole apparatus:
 
<langsyntaxhighlight lang="fexl">
\test_pipe =
(\next
Line 344 ⟶ 690:
next
)
</syntaxhighlight>
</lang>
 
Finally we call the test function:
<syntaxhighlight lang ="fexl">test_pipe;</langsyntaxhighlight>
{{out}}
<pre>
Line 367 ⟶ 713:
Good bye from parent.
test_pipe completed successfully.
</pre>
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
#g
."Kezd!\n"
§child fork sto childpid
@childpid wait
@childpid ."child pid ez volt: " printnl
end
child: ."Én a child vagyok!\n"
#d 3.14 printnl
2 sleep
end
{ „childpid” }
</syntaxhighlight>
{{out}}
<pre>
Kezd!
Én a child vagyok!
+3.14000000000000
child pid ez volt: 2123
</pre>
 
 
=={{header|Peri}}==
<syntaxhighlight lang="Peri">
###sysinclude standard.uh
###sysinclude system.uh
#g
."Start!\n"
§child fork sto childpid
@childpid wait
@childpid ."This was the child pid: " printnl
end
child: ."I am the child!\n"
#d 3.14 printnl
2 sleep
end
{ „childpid” }
</syntaxhighlight>
 
{{out}}
<pre>
Start!
I am the child!
+3.14000000000000
This was the child pid: 6261
 
</pre>
 
Line 374 ⟶ 769:
The [https://golang.org/pkg/os/exec <code>os/exec</code>] package offers a higher level interface and may be simpler in some situations.
For the purpose of this task though, there is little difference.
<langsyntaxhighlight lang="go">package main
 
import (
Line 399 ⟶ 794:
fmt.Println(err)
}
}</langsyntaxhighlight>
{{out}}
<pre>PID: 28044
Line 410 ⟶ 805:
 
For the subprocess this example uses Cygwin's bash shell and commands running under MS Windows.
<langsyntaxhighlight lang="groovy">println "BEFORE PROCESS"
Process p = Runtime.runtime.exec('''
C:/cygwin/bin/sh -c "
Line 426 ⟶ 821:
}
p.waitFor()
println "AFTER PROCESS"</langsyntaxhighlight>
 
Output:
Line 439 ⟶ 834:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Posix.Process
 
main = do
forkProcess (putStrLn "This is the new process")
putStrLn "This is the original process"</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">SYSTEM( RUN )
 
WRITE(Messagebox='?Y', IOStat=ios) "Another Fork?"
Line 456 ⟶ 851:
BEEP("c e g 'c")
WRITE(Messagebox="!") "Waiting ..."
ALARM(999) ! quit immediately </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
if (fork()|runerr(500)) = 0 then
write("child")
Line 466 ⟶ 861:
write("parent")
}
end</langsyntaxhighlight>
Notes:
* Fork should not fail. If an error 500 is generated there is a problem.
Line 473 ⟶ 868:
=={{header|J}}==
This example works by calling fork in a shared object library of Ubuntu 14.04.1 LTS . The verb given to adverb Fork evaluates in the child process.
<syntaxhighlight lang="j">
<lang J>
load'dll'
Fork =: (('Error'"_)`('Parent'"_)`)(@.([: >: [: * '/lib/x86_64-linux-gnu/libc-2.19.so __fork > x' cd [: i. 0&[))</langsyntaxhighlight>
The child process explicitly exits remaining as a zombie until the parent terminates.
<pre>
Line 498 ⟶ 893:
=={{header|Java}}==
{{trans|NetRexx}}
<syntaxhighlight lang="java">
<lang Java>
import java.io.IOException;
import java.io.InputStreamReader;
Line 537 ⟶ 932:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 551 ⟶ 946:
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">println("Parent running.")
@async(begin sleep(1); println("This is the child process."); sleep(2); println("Child again.") end)
sleep(2)
println("This is the parent process again.")
sleep(2)
println("Parent again.")
</syntaxhighlight>{{output}}<pre>
Parent running.
This is the child process.
This is the parent process again.
Child again.
Parent again.
</pre>
 
=={{header|Kotlin}}==
{{trans|NetRexx}}
<syntaxhighlight lang="scala">// version 1.1.51
 
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.IOException
 
fun main(args: Array<String>) {
try {
val pb = ProcessBuilder()
val currentUser = pb.environment().get("USER")
val command = listOf("ps", "-f", "U", currentUser)
pb.command(command)
val proc = pb.start()
val isr = InputStreamReader(proc.inputStream)
val br = BufferedReader(isr)
var line: String? = "Output of running $command is:"
while(true) {
println(line)
line = br.readLine()
if (line == null) break
}
}
catch (iox: IOException) {
iox.printStackTrace()
}
}</syntaxhighlight>
 
Sample output (Ubuntu 14.04):
<pre>
Output of running [ps, -f, U, user1] is:
UID PID PPID C STIME TTY STAT TIME CMD
user1 1401 1387 0 00:13 ? Ss 0:00 init --user
.....
user1 2687 2425 0 00:21 pts/8 Sl+ 0:00 java -jar fork.jar
user1 2699 2687 0 00:21 pts/8 R+ 0:00 ps -f U user1
</pre>
 
=={{header|Lasso}}==
Lasso is multithreaded by design.
You can fork of an independent thread at anytime using split_thread. The second thread will inherit all local variables declared before it is split.
<langsyntaxhighlight Lassolang="lasso">local(mydata = 'I am data one')
 
split_thread => {
Line 569 ⟶ 1,017:
stdoutnl(#mydata)
#mydata = 'Aha, I am still in the original thread'
}</langsyntaxhighlight>
Output:
<pre>I am data one
Line 576 ⟶ 1,024:
Aha, I am still in the original thread
</pre>
 
=={{header|LFE}}==
 
{{trans|Erlang}}
 
You can run this in the REPL as-is:
 
<syntaxhighlight lang="lisp">
(defun start ()
(spawn (lambda () (child))))
 
(defun child ()
(lfe_io:format "This is the new process~n" '()))
</syntaxhighlight>
 
=={{header|Lua}}==
{{libheader|POSIX}}
<langsyntaxhighlight Lualang="lua">local posix = require 'posix'
 
local pid = posix.fork()
Line 588 ⟶ 1,050:
else
error("unable to fork")
end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This code will run a standalone Mathematica kernel, putting the result of a command in a temporary file:
<langsyntaxhighlight Mathematicalang="mathematica">commandstring = First[$CommandLine] <> " -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""
->"MathKernel -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""
 
Run[commandstring]
->0</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 626 ⟶ 1,088:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 644 ⟶ 1,106:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(let (pid (fork (println "Hello from child")))
(cond
((nil? pid) (throw-error "Unable to fork"))
('t (wait-pid pid))))</langsyntaxhighlight>
 
=={{header|Nimrod}}==
<lang nimrod>import posix
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import posix
var pid = fork()
if pid < 0:
#echo error"Error forking a child"
elif pid > 0:
#echo "This is the parent, process and pidits ischild processhas id of", childpid, '.'
# Further parent stuff.
else:
#echo "This is the child process."
# Further child stuff.</syntaxhighlight>
quit()
 
# further Parent stuff here</lang>
{{out}}
<pre>This is the parent process and its child has id 8506.
This is the child process.</pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma";;
let pid = Unix.fork ();;
if pid > 0 then
print_endline "This is the original process"
else
print_endline "This is the new process";;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
===version 1 using REPLY===
<langsyntaxhighlight lang="oorexx">sub=.fork~new
sub~sub
Call syssleep 1
Line 687 ⟶ 1,153:
Say 'subroutine' time()
Call syssleep 1
End</langsyntaxhighlight>
{{out}}
<pre>subroutine 10:53:27
Line 700 ⟶ 1,166:
 
===version 2 using START===
<langsyntaxhighlight lang="oorexx">sub=.fork~new
sub~start('start_working')
 
Line 714 ⟶ 1,180:
Say 'subroutine' time()
Call syssleep 1
End</langsyntaxhighlight>
{{out}}
<pre>subroutine 14:55:10
Line 729 ⟶ 1,195:
Mozart's support for distributed programming is quite unique. We can send code accross the network and share data by lexical scoping. It doesn't matter whether we create the process on the local machine (as in this example) or on some remote computer as long as we have ssh access (or some similar method) and Mozart is installed.
 
<langsyntaxhighlight lang="oz">declare
ParentVar1 = "parent data"
ParentVar2
Line 758 ⟶ 1,224:
%% exit child process
{RM close}
{Show ParentVar2} %% print "childData"</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This is a PARI implementation which uses <code>fork()</code> via PARI's <code>pari_daemon</code>. Of course <code>fork()</code> could be used directly.
 
<langsyntaxhighlight Clang="c">void
foo()
{
Line 770 ⟶ 1,236:
else
pari_printf("Fork\n");
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 776 ⟶ 1,242:
In the child code, you may have to re-open database handles and such.
 
<langsyntaxhighlight lang="perl">FORK:
if ($pid = fork()) {
# parent code
Line 800 ⟶ 1,266:
warn '[' . localtime() . "] Unable to fork - $!";
exit(0);
}</langsyntaxhighlight>
 
Obviously you could do a Fork in a lot less lines, but this code covers all the bases.
Line 806 ⟶ 1,272:
Another example using [http://search.cpan.org/perldoc?Proc::Fork Proc::Fork] module:
 
<langsyntaxhighlight lang="perl">use Proc::Fork;
run_fork {
child {
Line 814 ⟶ 1,280:
# parent code ...
}
};</langsyntaxhighlight>
 
Or:
<langsyntaxhighlight lang="perl">use Proc::Fork;
# parent code ...
run_fork {
Line 824 ⟶ 1,290:
}
};
# parent code continues ...</langsyntaxhighlight>
 
More complex example with retries and error handling:
<langsyntaxhighlight lang="perl">use Proc::Fork;
run_fork {
child {
Line 841 ⟶ 1,307:
# error handling ...
}
};</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
Phix has create_thread which creates a separate thread, with its own call stack, but sharing common data (like most fork examples here).<br>
{{works with|Rakudo Star|2013-01}}
To run something completely independently, use system() or system_exec(), depending on whether you want a shell and/or to wait for a result.
<lang perl6>use NativeCall;
<!--<syntaxhighlight lang="phix">(notonline)-->
sub fork() returns Int is native { ... }
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">mythread</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"mythread"</span>
<span style="color: #000000;">exit_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">hThread</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_thread</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"mythread"</span><span style="color: #0000FF;">),{})</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"main carries on"</span>
<span style="color: #000000;">wait_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hThread</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
or
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"calc"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
if fork() -> $pid {
print "I am the proud parent of $pid.\n";
}
else {
print "I am a child. Have you seen my mommy?\n";
}</lang>
{{out}}
<pre>I am the proud parent of 17691.
I am a child. Have you seen my mommy?</pre>
=={{header|PHP}}==
{{trans|C}}
<langsyntaxhighlight lang="php"><?php
$pid = pcntl_fork();
if ($pid == 0)
Line 867 ⟶ 1,339:
else
echo "ERROR: Something went wrong\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(unless (fork) # In child process
(println *Pid) # Print the child's PID
(bye) ) # and terminate</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
ATTACH SOLVE (X) THREAD (T5);
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">lvars ress;
if sys_fork(false) ->> ress then
;;; parent
Line 886 ⟶ 1,358:
else
printf('In child\n');
endif;</langsyntaxhighlight>
{{omit from|PureBasic}}
 
=={{header|Python}}==
{{works with|Python|2.5}}
<langsyntaxhighlight lang="python">import os
 
pid = os.fork()
Line 897 ⟶ 1,369:
# parent code
else:
# child code</langsyntaxhighlight>
 
=={{header|R}}==
Two examples. The first is a higher level interface to fork system call. The second is a lower level interface for forking.
<syntaxhighlight lang="r">
p <- parallel::mcparallel({
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
TRUE
})
cat("Main pid: ", Sys.getpid(), "\n")
parallel::mccollect(p)
 
p <- parallel:::mcfork()
if (inherits(p, "masterProcess")) {
Sys.sleep(1)
cat("\tChild pid: ", Sys.getpid(), "\n")
parallel:::mcexit(, TRUE)
}
cat("Main pid: ", Sys.getpid(), "\n")
unserialize(parallel:::readChildren(2))</syntaxhighlight>
 
Output:
<pre>
Main pid: 331042
Child pid: 331052
$`331052`
[1] TRUE
 
Main pid: 331042
Child pid: 331054
[1] TRUE
</pre>
 
=={{header|Racket}}==
Line 904 ⟶ 1,408:
are both. First, run some subprocess independently of Racket:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define-values [P _out _in _err]
Line 911 ⟶ 1,415:
;; wait for process to end, print messages as long as it runs
(let loop () (unless (sync/timeout 10 P) (printf "Still running...\n") (loop)))
</syntaxhighlight>
</lang>
 
Output:
Line 924 ⟶ 1,428:
Second, using fork() in its raw form, which is doable in racket, but as unsafe as you'd expect it to be:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require ffi/unsafe)
(define fork (get-ffi-obj 'fork #f (_fun -> _int)))
(printf ">>> fork() => ~s\n" (fork))
</syntaxhighlight>
</lang>
 
Output:
Line 936 ⟶ 1,440:
>>> fork() => 0
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.06}}
<syntaxhighlight lang="raku" line>use NativeCall;
sub fork() returns int32 is native { ... }
 
if fork() -> $pid {
print "I am the proud parent of $pid.\n";
}
else {
print "I am a child. Have you seen my mommy?\n";
}</syntaxhighlight>
{{out}}
<pre>I am the proud parent of 17691.
I am a child. Have you seen my mommy?</pre>
 
=={{header|REXX}}==
This function &nbsp; '''only''' &nbsp; works with Regina REXX.
<langsyntaxhighlight lang="rexx">child = fork()</langsyntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">pid = fork
if pid
# parent code
else
# child code
end</langsyntaxhighlight>
or
<langsyntaxhighlight lang="ruby">fork do
# child code
end
# parent code</langsyntaxhighlight>
 
=={{header|Run BASICRust}}==
This uses the nix(0.15) crate. The code has been tested on Linux, OS X.
You can run a program until that program executes a wait statement.
<syntaxhighlight lang="rust">use nix::unistd::{fork, ForkResult};
Once the program waits,you can use it's functions.
use std::process::id;
 
<lang runbasic>run "someProgram.bas",#handle
fn main() {
render #handle ' this runs the program until it waits
match fork() {
' both the parent and child are running
Ok(ForkResult::Parent { child, .. }) => {
' --------------------------------------------------------
println!(
' You can also call a function in the someProgram.bas program.
"This is the original process(pid: {}). New child has pid: {}",
' For example if it had a DisplayBanner Funciton.
id(),
#handle DisplayBanner("Welcome!")</lang>
child
);
}
Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()),
Err(_) => println!("Something went wrong."),
}
}
</syntaxhighlight>output<syntaxhighlight lang="text">This is the original process(pid: 88637). New child has pid: 88651
This is the new process(pid: 88651).
</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
===A Linux version===
<langsyntaxhighlight lang="scala">import java.io.IOException
 
object Fork extends App {
Line 984 ⟶ 1,514:
case iox: IOException => iox.printStackTrace()
}
}</langsyntaxhighlight>
===A Windows version===
<langsyntaxhighlight lang="scala">import java.io.IOException
 
object Fork extends App {
Line 999 ⟶ 1,529:
case iox: IOException => iox.printStackTrace()
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var x = 42;
{ x += 1; say x }.fork.wait; # x is 43 here
say x; # but here is still 42</syntaxhighlight>
 
=={{header|Slate}}==
The following built-in method uses the cloneSystem primitive (which calls fork()) to fork code. The parent and the child both get a socket from a socketpair which they can use to communicate. The cloneSystem is currently unimplemented on windows (since there isn't a fork() system call).<langsyntaxhighlight lang="slate">p@(Process traits) forkAndDo: b
[| ret |
(ret := lobby cloneSystem)
first ifTrue: [p pipes addLast: ret second. ret second]
ifFalse: [[p pipes clear. p pipes addLast: ret second. b applyWith: ret second] ensure: [lobby quit]]
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">'Here I am' displayNl.
|a|
a := [
Line 1,020 ⟶ 1,555:
"wait to avoid terminating first the parent;
a better way should use semaphores"
(Delay forSeconds: 10) wait.</langsyntaxhighlight>
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">case Posix.Process.fork () of
SOME pid => print "This is the original process\n"
| NONE => print "This is the new process\n";</langsyntaxhighlight>
 
=={{header|Symsyn}}==
 
<syntaxhighlight lang="symsyn">
| parent
ssx 'R child'
wait 'childevent'
'child is running...' []
'child will end...' []
post 'dieevent'
delay 5000
</syntaxhighlight>
<syntaxhighlight lang="symsyn">
| child
post 'childevent'
'I am child...' []
wait 'dieevent'
</syntaxhighlight>
From the command line in Windows :
>SSX parent
{{out}}
<syntaxhighlight lang="symsyn">
SSX Started...
Prog 1 parent Running @ 7/12/2020 13:29:14
1: R child
Prog 2 child Running @ 7/12/2020 13:29:14
2: I am child...
1: child is running...
1: child will end...
Prog 2 child Ended @ 7/12/2020 13:29:14
Prog 1 parent Ended @ 7/12/2020 13:29:19
SSX Ended...
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 1,037 ⟶ 1,605:
Example:
 
<langsyntaxhighlight lang="tcl">package require Expect
# or
package require Tclx
Line 1,055 ⟶ 1,623:
}
}
}</langsyntaxhighlight>
 
In most cases though, one is not interested in spawning a copy of the process one already has, but rather wants a different process. When using POSIX APIs, this has to be done by first forking and then having the child use the exec system call to replace itself with a different program. The Tcl <code>[http://www.tcl.tk/man/tcl8.5/TclCmd/exec.htm exec]</code> command does this fork&exec combination — in part because non-Unix OSs typicallly don't have "make a copy of parent process" as an intermediate step when spawning new processes.
Line 1,062 ⟶ 1,630:
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">needs shell
getpid is-data PID
[ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">i=0
(while test $i -lt 10; do
sleep 1
Line 1,078 ⟶ 1,646:
echo "Parent process"
i=`expr $i + 1`
done</langsyntaxhighlight>
 
This uses the operator <tt>&</tt> to run the child process and the parent process at the same time. The output for the next 10 seconds is "Child process" every 1 second, and "Parent process" every 2 seconds. Both processes inherit <tt>i=0</tt>, but each process has its own <tt>i</tt> variable because processes are independent.
Line 1,086 ⟶ 1,654:
{{works with|bash}}
 
<langsyntaxhighlight lang="bash">(for ((i=0;i<10;i++)); do sleep 1; echo "Child process"; done) &
for ((i=0;i<5;i++)); do
sleep 2
echo "Parent process"
done</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
Demonstrating a subshell getting forked, and running concurrently with the original process
 
<langsyntaxhighlight lang="bash">(echo "Process 1" >&2 ;sleep 5; echo "1 done" ) | (echo "Process 2";cat;echo "2 done")</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">do (fork sleep.1
prn.1)
prn.2</langsyntaxhighlight>
 
=={{header|X86 AssemblyWren}}==
{{trans|C}}
{{works with|NASM|Linux}}<br>
The ability to call C library functions such as ''fork'' may be added to Wren-cli in the next release. In the meantime, we embed the following Wren script in a minimal C host (no error checking) to complete this task.
While it IS possible to use native syscalls to create forks, it's not recommended. sys_fork requires manual setup for the pt_regs structure. It further requires you to enter kernal space using sysenter/exit pairs, setup the registers then call sys_fork. Linking to the C library is simply less work for user space forks. The only time it's really used is during debugging applications.
<syntaxhighlight lang="wren">/* Fork.wren */
<lang asm>
 
extern fork
class C {
extern printf
foreign static fork()
 
foreign static usleep(usec)
 
foreign static wait()
}
 
var pid = C.fork()
if (pid == 0) {
C.usleep(10000)
System.print("\tchild process: done")
} else if (pid < 0) {
System.print("fork error")
} else {
System.print("waiting for child %(pid)...")
System.print("child %(C.wait()) finished")
}</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include "wren.h"
 
void C_fork(WrenVM* vm) {
pid_t pid = fork();
wrenSetSlotDouble(vm, 0, (double)pid);
}
 
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
 
void C_wait(WrenVM* vm) {
pid_t pid = wait(NULL);
wrenSetSlotDouble(vm, 0, (double)pid);
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "fork()") == 0) return C_fork;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
if (isStatic && strcmp(signature, "wait()") == 0) return C_wait;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Fork.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{out}}
Sample output:
<pre>
waiting for child 15274...
child process: done
child 15274 finished
</pre>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<syntaxhighlight lang="asm">
option casemap:none
 
windows64 equ 1
linux64 equ 3
 
ifndef __THREAD_CLASS__
__THREAD_CLASS__ equ 1
 
if @Platform eq windows64
option dllimport:<kernel32>
CreateThread proto :qword, :qword, :qword, :qword, :dword, :qword
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
GetProcessHeap proto
option dllimport:<none>
exit equ ExitProcess
elseif @Platform eq linux64
pthread_create proto :qword, :qword, :qword, :qword
malloc proto :qword
free proto :qword
exit proto :dword
endif
 
printf proto :qword, :vararg
 
CLASS thread
CMETHOD createthread
ENDMETHODS
tid dq ?
hThread dq ?
ENDCLASS
 
METHOD thread, Init, <VOIDARG>, <>
mov rax, thisPtr
ret
ENDMETHOD
 
METHOD thread, createthread, <VOIDARG>, <>, lpCode:qword, arg:qword
local z:qword,x:qword
 
mov rbx, thisPtr
assume rbx:ptr thread
mov z, lpCode
mov x, 0
.if arg != 0
mov x, arg
.endif
if @Platform eq windows64
invoke CreateThread, 0, 0, z, x, 0, addr [rbx].tid
.if rax == 0
mov rax, -1
ret
.endif
elseif @Platform eq linux64
invoke pthread_create, addr [rbx].tid, 0, z, x
.if rax != 0
mov rax, -1
ret
.endif
endif
mov [rbx].hThread, rax
assume rbx:nothing
ret
ENDMETHOD
 
METHOD thread, Destroy, <VOIDARG>, <>
;; We should close all thread handles here..
;; But I don't care. In this example, exit does it for me. :]
ret
ENDMETHOD
 
endif ;;__THREAD_CLASS__
 
thChild proto
 
.data
 
.code
main proc
local pThread:ptr thread
 
mov pThread, _NEW(thread)
invoke printf, CSTR("--> Main thread spwaning child thread...",10)
lea rax, thChild
pThread->createthread(rax, 0)
_DELETE(pThread)
;; Just a loop so Exit doesn't foobar the program.
;; No reason to include and call Sleep just for this.. -.-
mov rcx, 20000
@@:
add rax, 1
loop @B
invoke exit, 0
ret
main endp
 
thChild proc
invoke printf, CSTR("--> Goodbye, World! from a child.... thread.",10)
mov rax, 0
ret
thChild endp
end
</syntaxhighlight>
 
===NASM===
I've written a subroutine that prints out any positive value. It lives on my desktop and you can't find it on rosetta code.
I've also written a sleep subroutine and you can find that in the Sleep task on this site.
 
<syntaxhighlight lang="x86asm">
; x86_64 linux nasm
 
%include "/home/james/Desktop/ASM_LIB/Print.asm"
%include "/home/james/Desktop/ASM_LIB/Sleep.asm"
 
section .text
global _start
_start:
call fork
cmp eax, 0
je _child
jg _parent
jmp _exit
_parent:
push p_msg
call printf
jmp _exit
_child:
push c_msg
call printf
jmp _exit
_exit:
push 0x1
mov eax, 1
push eax
int 0x80
ret
section .data
 
c_msg db "Printed from Child process",13,10,0
p_msg parent: db "Printed from Parent: process",13,10,0
child: db "Child: "
</lang>
newLine: db 10
 
section .text
 
global _start
 
_start:
mov rax, 57 ; fork syscall
syscall
cmp rax, 0 ; if the return value is 0, we're in the child process
je printChild
 
printParent: ; else it's the child's PID, we're in the parent
 
mov rax, 1
mov rdi, 1
mov rsi, parent
mov rdx, 8
syscall
 
mov rax, 39 ; sys_getpid
syscall
mov rdi, rax
call Print_Unsigned
 
mov rax, 1
mov rdi, 1
mov rsi, newLine
mov rdx, 1
syscall
 
mov rdi, 1 ; sleep so the child process can print befor the parent exits
call Sleep ; you might not see the child output if you don't do this
 
jmp exit
 
printChild:
 
mov rdi, 1
call Sleep ; sleep and wait for parent to print to screen first
 
mov rax, 1
mov rdi, 1
mov rsi, child
mov rdx, 7
syscall
 
mov rax, 39 ; sys_getpid
syscall
mov rdi, rax
call Print_Unsigned
 
mov rax, 1
mov rdi, 1
mov rsi, newLine
mov rdx, 1
syscall
exit:
mov rax, 60
mov rdi, 0
syscall
</syntaxhighlight>
 
=={{header|XPL0}}==
Works on Raspberry Pi.
<syntaxhighlight lang="xpl0">int Key, Process;
[Key:= SharedMem(4); \allocate 4 bytes of memory common to both processes
Process:= Fork(1); \start one child process
case Process of
0: [Lock(Key); Text(0, "Rosetta"); CrLf(0); Unlock(Key)]; \parent process
1: [Lock(Key); Text(0, "Code"); CrLf(0); Unlock(Key)] \child process
other [Lock(Key); Text(0, "Error"); CrLf(0); Unlock(Key)];
Join(Process); \wait for child process to finish
]</syntaxhighlight>
 
{{out}}
<pre>
Rosetta
Code
</pre>
 
=={{header|zkl}}==
{{works with|Unix}}
This just tells the Unix shell to run the process in the background
<langsyntaxhighlight lang="zkl">zkl: System.cmd("ls &")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,159 ⟶ 1,995:
{{omit from|Unlambda|Does not have concurrency or background processes.}}
{{omit from|Retro|No concurrency in the standard VM}}
{{omit from|SAS}}
{{omit from|Stata}}
{{omit from|VBA}}
{{omit from|ZX Spectrum Basic|Does not support multiple processes.}}
9,476

edits