Fork: Difference between revisions

2,682 bytes added ,  1 year ago
m
syntax highlighting fixup automation
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 8:
=={{header|Ada}}==
{{libheader|POSIX}}
<langsyntaxhighlight lang="ada">with Ada.Text_IO,
POSIX.Process_Identification,
POSIX.Unsafe_Process_Primitives;
Line 25:
when others =>
Put_Line ("Something went wrong.");
end Fork;</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">
var pid = fork()
switch (pid) {
Line 41:
break
}
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
Line 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 57:
print("ERROR: Something went wrong")
FI
)</langsyntaxhighlight>
Output:
<pre>
Line 65:
 
=={{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|BaCon}}==
<langsyntaxhighlight lang="freebasic">' Fork
pid = FORK
IF pid = 0 THEN
Line 84:
ELSE
PRINT "Error in fork"
ENDIF</langsyntaxhighlight>
 
{{out}}
Line 100:
While you cannot fork into asynchronous subroutines conventionally, there are workarounds involving the <code>start</code> command.
 
<langsyntaxhighlight lang="dos">
@echo off
 
Line 150:
if exist output1.txt echo mySubroutine1 has been run > output3.txt
exit
</syntaxhighlight>
</lang>
 
Output:
Line 173:
 
=={{header|C}}==
{{libheader|POSIX}}<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 194:
 
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text">waiting for child 3604...
child process: done
child 3604 finished</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Threading;
 
Line 218:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 224:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="cpp">#include<iostream>
#include<unistd.h>
 
Line 245:
 
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 258:
(if (zero? exit)
(do-something-with out)
(report-errors-in err))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 265:
{{works with|GnuCOBOL}}
 
<langsyntaxhighlight lang="cobol"> identification division.
program-id. forking.
 
Line 294:
 
goback.
end program forking.</langsyntaxhighlight>
 
{{out}}
Line 312:
{{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}}==
<langsyntaxhighlight Dlang="d">import core.thread;
import std.stdio;
 
Line 327:
}).start;
writeln("Main thread.");
}</langsyntaxhighlight>
 
{{out}}
Line 336:
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.
 
<langsyntaxhighlight DCLlang="dcl">$! looper.com procedure
$ i = 10
$ loop:
Line 342:
$ wait 'p1
$ i = i - 1
$ if i .gt. 0 then $ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ spawn /nowait /notify @looper 0::2 ! up to 8 parameters are allowed
Line 360:
$</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).
<langsyntaxhighlight DCLlang="dcl">$! fork.com procedure
$ set noverify ! detached processes have verify on by default which clutters up the output log file
$ @looper 0::2</langsyntaxhighlight>
{{out}}
<pre>$ run /detach sys$system:loginout /input = fork /output = fork
Line 379:
{{libheader| System.Threading}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Fork_app;
 
Line 402:
TTask.WaitForAll(t);
Readln;
end.</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Fork do
def start do
spawn(fn -> child end)
Line 414:
end
 
Fork.start</langsyntaxhighlight>
 
{{out}}
Line 423:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(fork).
-export([start/0]).
 
Line 431:
 
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</langsyntaxhighlight>
 
=={{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 458:
 
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 546:
)
)
</syntaxhighlight>
</lang>
 
Next, we define a test_pipe function to test the whole apparatus:
 
<langsyntaxhighlight lang="fexl">
\test_pipe =
(\next
Line 623:
next
)
</syntaxhighlight>
</lang>
 
Finally we call the test function:
<syntaxhighlight lang ="fexl">test_pipe;</langsyntaxhighlight>
{{out}}
<pre>
Line 649:
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
#g
."Kezd!\n"
Line 661:
end
{ „childpid” }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 673:
=={{header|FreeBASIC}}==
En Windows sin usar windows.bi, podemos usar un comando vbscript
<langsyntaxhighlight lang="freebasic">
Function script(s As String) As String
Dim As String g = _
Line 706:
Kill "script.vbs"
Sleep
</syntaxhighlight>
</lang>
 
 
Line 714:
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 739:
fmt.Println(err)
}
}</langsyntaxhighlight>
{{out}}
<pre>PID: 28044
Line 750:
 
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 766:
}
p.waitFor()
println "AFTER PROCESS"</langsyntaxhighlight>
 
Output:
Line 779:
 
=={{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 796:
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 806:
write("parent")
}
end</langsyntaxhighlight>
Notes:
* Fork should not fail. If an error 500 is generated there is a problem.
Line 813:
=={{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 838:
=={{header|Java}}==
{{trans|NetRexx}}
<syntaxhighlight lang="java">
<lang Java>
import java.io.IOException;
import java.io.InputStreamReader;
Line 877:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 892:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">println("Parent running.")
@async(begin sleep(1); println("This is the child process."); sleep(2); println("Child again.") end)
sleep(2)
Line 898:
sleep(2)
println("Parent again.")
</langsyntaxhighlight>{{output}}<pre>
Parent running.
This is the child process.
Line 908:
=={{header|Kotlin}}==
{{trans|NetRexx}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import java.io.InputStreamReader
Line 933:
iox.printStackTrace()
}
}</langsyntaxhighlight>
 
Sample output (Ubuntu 14.04):
Line 948:
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 962:
stdoutnl(#mydata)
#mydata = 'Aha, I am still in the original thread'
}</langsyntaxhighlight>
Output:
<pre>I am data one
Line 976:
You can run this in the REPL as-is:
 
<langsyntaxhighlight lang="lisp">
(defun start ()
(spawn (lambda () (child))))
Line 982:
(defun child ()
(lfe_io:format "This is the new process~n" '()))
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
{{libheader|POSIX}}
<langsyntaxhighlight Lualang="lua">local posix = require 'posix'
 
local pid = posix.fork()
Line 995:
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 1,033:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,051:
 
=={{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|Nim}}==
<langsyntaxhighlight lang="nim">import posix
var pid = fork()
Line 1,067:
else:
echo "This is the child process."
# Further child stuff.</langsyntaxhighlight>
 
{{out}}
Line 1,075:
=={{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 1,098:
Say 'subroutine' time()
Call syssleep 1
End</langsyntaxhighlight>
{{out}}
<pre>subroutine 10:53:27
Line 1,111:
 
===version 2 using START===
<langsyntaxhighlight lang="oorexx">sub=.fork~new
sub~start('start_working')
 
Line 1,125:
Say 'subroutine' time()
Call syssleep 1
End</langsyntaxhighlight>
{{out}}
<pre>subroutine 14:55:10
Line 1,140:
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 1,169:
%% 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 1,181:
else
pari_printf("Fork\n");
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 1,187:
In the child code, you may have to re-open database handles and such.
 
<langsyntaxhighlight lang="perl">FORK:
if ($pid = fork()) {
# parent code
Line 1,211:
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 1,217:
Another example using [http://search.cpan.org/perldoc?Proc::Fork Proc::Fork] module:
 
<langsyntaxhighlight lang="perl">use Proc::Fork;
run_fork {
child {
Line 1,225:
# parent code ...
}
};</langsyntaxhighlight>
 
Or:
<langsyntaxhighlight lang="perl">use Proc::Fork;
# parent code ...
run_fork {
Line 1,235:
}
};
# parent code continues ...</langsyntaxhighlight>
 
More complex example with retries and error handling:
<langsyntaxhighlight lang="perl">use Proc::Fork;
run_fork {
child {
Line 1,252:
# error handling ...
}
};</langsyntaxhighlight>
 
=={{header|Phix}}==
Phix has create_thread which creates a separate thread, with its own call stack, but sharing common data (like most fork examples here).<br>
To run something completely independently, use system() or system_exec(), depending on whether you want a shell and/or to wait for a result.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<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>
Line 1,267:
<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>
<!--</langsyntaxhighlight>-->
or
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
{{trans|C}}
<langsyntaxhighlight lang="php"><?php
$pid = pcntl_fork();
if ($pid == 0)
Line 1,284:
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 1,303:
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 1,314:
# 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">
<lang R>
p <- parallel::mcparallel({
Sys.sleep(1)
Line 1,334:
}
cat("Main pid: ", Sys.getpid(), "\n")
unserialize(parallel:::readChildren(2))</langsyntaxhighlight>
 
Output:
Line 1,353:
are both. First, run some subprocess independently of Racket:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define-values [P _out _in _err]
Line 1,360:
;; 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 1,373:
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 1,389:
(formerly Perl 6)
{{Works with|rakudo|2016.06}}
<syntaxhighlight lang="raku" perl6line>use NativeCall;
sub fork() returns int32 is native { ... }
 
Line 1,397:
else {
print "I am a child. Have you seen my mommy?\n";
}</langsyntaxhighlight>
{{out}}
<pre>I am the proud parent of 17691.
Line 1,404:
=={{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 BASIC}}==
Line 1,423:
Once the program waits,you can use it's functions.
<langsyntaxhighlight lang="runbasic">run "someProgram.bas",#handle
render #handle ' this runs the program until it waits
' both the parent and child are running
Line 1,429:
' You can also call a function in the someProgram.bas program.
' For example if it had a DisplayBanner Funciton.
#handle DisplayBanner("Welcome!")</langsyntaxhighlight>
 
=={{header|Rust}}==
This uses the nix(0.15) crate. The code has been tested on Linux, OS X.
<langsyntaxhighlight lang="rust">use nix::unistd::{fork, ForkResult};
use std::process::id;
 
Line 1,449:
}
}
</langsyntaxhighlight>output<syntaxhighlight lang="text">This is the original process(pid: 88637). New child has pid: 88651
This is the new process(pid: 88651).
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
{{libheader|Scala}}
===A Linux version===
<langsyntaxhighlight lang="scala">import java.io.IOException
 
object Fork extends App {
Line 1,471:
case iox: IOException => iox.printStackTrace()
}
}</langsyntaxhighlight>
===A Windows version===
<langsyntaxhighlight lang="scala">import java.io.IOException
 
object Fork extends App {
Line 1,486:
case iox: IOException => iox.printStackTrace()
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var x = 42;
{ x += 1; say x }.fork.wait; # x is 43 here
say x; # but here is still 42</langsyntaxhighlight>
 
=={{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,512:
"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">
<lang Symsyn>
| parent
ssx 'R child'
Line 1,530:
post 'dieevent'
delay 5000
</syntaxhighlight>
</lang>
<syntaxhighlight lang="symsyn">
<lang Symsyn>
| child
post 'childevent'
'I am child...' []
wait 'dieevent'
</syntaxhighlight>
</lang>
From the command line in Windows :
>SSX parent
{{out}}
<langsyntaxhighlight lang="symsyn">
SSX Started...
Prog 1 parent Running @ 7/12/2020 13:29:14
Line 1,551:
Prog 1 parent Ended @ 7/12/2020 13:29:19
SSX Ended...
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Line 1,562:
Example:
 
<langsyntaxhighlight lang="tcl">package require Expect
# or
package require Tclx
Line 1,580:
}
}
}</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,587:
 
=={{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,603:
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,611:
{{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|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Fork()
Line 1,638:
End Sub
 
End Module</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">do (fork sleep.1
prn.1)
prn.2</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
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.
<langsyntaxhighlight lang="ecmascript">/* fork.wren */
 
class C {
Line 1,667:
System.print("waiting for child %(pid)...")
System.print("child %(C.wait()) finished")
}</langsyntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,737:
free(script);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,749:
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<langsyntaxhighlight lang="asm">
option casemap:none
 
Line 1,853:
thChild endp
end
</syntaxhighlight>
</lang>
 
===NASM===
Line 1,859:
I've also written a sleep subroutine and you can find that in the Sleep task on this site.
 
<langsyntaxhighlight lang="x86asm">
; x86_64 linux nasm
 
Line 1,931:
mov rdi, 0
syscall
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
Works on Raspberry Pi.
<langsyntaxhighlight XPL0lang="xpl0">int Key, Process;
[Key:= SharedMem(4); \allocate 4 bytes of memory common to both processes
Process:= Fork(1); \start one child process
Line 1,943:
other [Lock(Key); Text(0, "Error"); CrLf(0); Unlock(Key)];
Join(Process); \wait for child process to finish
]</langsyntaxhighlight>
 
{{out}}
Line 1,954:
{{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>
10,333

edits