Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

3
Task/Fork/00-META.yaml Normal file
View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Fork
note: Programming environment operations

5
Task/Fork/00-TASK.txt Normal file
View file

@ -0,0 +1,5 @@
;Task:
Spawn a new [[process]] which can run simultaneously with, and independently of, the original parent process.
<br><br>

View file

@ -0,0 +1,11 @@
main:
(
INT pid;
IF (pid:=fork)=0 THEN
print("This is new process")
ELIF pid>0 THEN
print("This is the original process")
ELSE
print("ERROR: Something went wrong")
FI
)

18
Task/Fork/Ada/fork.ada Normal file
View file

@ -0,0 +1,18 @@
with Ada.Text_IO,
POSIX.Process_Identification,
POSIX.Unsafe_Process_Primitives;
procedure Fork is
use Ada.Text_IO,
POSIX.Process_Identification,
POSIX.Unsafe_Process_Primitives;
begin
if Fork = Null_Process_ID then
Put_Line ("This is the new process.");
else
Put_Line ("This is the original process.");
end if;
exception
when others =>
Put_Line ("Something went wrong.");
end Fork;

View file

@ -0,0 +1,12 @@
var pid = fork()
switch (pid) {
case <0:
println ("fork error")
break
case 0:
println ("child")
break
default:
println ("parent")
break
}

View file

@ -0,0 +1,4 @@
MsgBox, 4, Fork, Start another process?
IfMsgBox, Yes
Run, %A_AhkPath% "%A_ScriptFullPath%"
MsgBox, 0, Fork, Stop this process.

View file

@ -0,0 +1,14 @@
' 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

View file

@ -0,0 +1,49 @@
@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

22
Task/Fork/C++/fork.cpp Normal file
View file

@ -0,0 +1,22 @@
#include<iostream>
#include<unistd.h>
int main()
{
pid_t pid = fork();
if (pid == 0)
{
std::cout << "This is the new process\n";
}
else if (pid > 0)
{
std::cout << "This is the original process\n";
}
else
{
std::cerr << "ERROR: Something went wrong\n";
}
return 0;
}

20
Task/Fork/C-sharp/fork.cs Normal file
View file

@ -0,0 +1,20 @@
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();
}
}
}

22
Task/Fork/C/fork-1.c Normal file
View file

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <err.h>
int main()
{
pid_t pid;
if (!(pid = fork())) {
usleep(10000);
printf("\tchild process: done\n");
} else if (pid < 0) {
err(1, "fork error");
} else {
printf("waiting for child %d...\n", (int)pid);
printf("child %d finished\n", (int)wait(0));
}
return 0;
}

3
Task/Fork/C/fork-2.c Normal file
View file

@ -0,0 +1,3 @@
waiting for child 3604...
child process: done
child 3604 finished

View file

@ -0,0 +1,30 @@
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.

View file

@ -0,0 +1,2 @@
(require '[clojure.java.shell :as shell])
(shell/sh "echo" "foo") ; evaluates to {:exit 0, :out "foo\n", :err ""}

View file

@ -0,0 +1,7 @@
(let [search (future (shell/sh "find" "." "-name" "needle.*" :dir haystack))]
(while (and (other-stuff-to-do?) (not (future-done? search)))
(do-other-stuff))
(let [{:keys [exit out err]} @search]
(if (zero? exit)
(do-something-with out)
(report-errors-in err))))

View file

@ -0,0 +1,5 @@
(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."))))

9
Task/Fork/D/fork.d Normal file
View file

@ -0,0 +1,9 @@
import core.thread;
import std.stdio;
void main() {
new Thread({
writeln("Spawned thread.");
}).start;
writeln("Main thread.");
}

7
Task/Fork/DCL/fork-1.dcl Normal file
View file

@ -0,0 +1,7 @@
$! looper.com procedure
$ i = 10
$ loop:
$ show time
$ wait 'p1
$ i = i - 1
$ if i .gt. 0 then $ goto loop

3
Task/Fork/DCL/fork-2.dcl Normal file
View file

@ -0,0 +1,3 @@
$! fork.com procedure
$ set noverify ! detached processes have verify on by default which clutters up the output log file
$ @looper 0::2

View file

@ -0,0 +1,23 @@
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.

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,9 @@
-module(fork).
-export([start/0]).
start() ->
erlang:spawn( fun() -> child() end ),
io:format("This is the original process~n").
child() ->
io:format("This is the new process~n").

View file

@ -0,0 +1,2 @@
c(fork).
fork:start().

View file

@ -0,0 +1,3 @@
USING: unix unix.process ;
[ "Hello form child" print flush 0 _exit ] [ drop "Hi from parent" print flush ] with-fork

View file

@ -0,0 +1,2 @@
fork \pid
print "pid = ";print pid;nl;

View file

@ -0,0 +1,87 @@
# (spawn child_fn next)
# Fork the child function as a process and return its pid, stdin, stdout, and
# stderr.
\spawn =
(
### Use error-checking versions of system routines
\pipe =
(\next
pipe \status\read\write
long_lt status 0 (die "pipe failed");
next read write
)
\dup2 =
(\oldfd\newfd\next
dup2 oldfd newfd \status
long_lt status 0 (die "dup2 failed");
next
)
\fdopen =
(\fd\mode\next
fdopen fd mode next;
die "fdopen failed"
)
\fork =
(\next
fork \pid
long_lt pid 0 (die "fork failed");
next pid
)
# Now here's the spawn function itself.
\child_fn\next
# First flush the parent's stdout and stderr to avoid any pending output
# accidentally getting pushed into the child's input. I've noticed this
# can happen when your script output is sent to a file or pipe instead of
# a console.
get_stdout \fh fflush fh \_
get_stderr \fh fflush fh \_
# Now create a series of pipes, each with a read and write side.
pipe \r_in\w_in
pipe \r_out\w_out
pipe \r_err\w_err
fork \pid
long_eq pid 0
(
# Child process.
# Duplicate one side of each pipe into stdin, stdout, and stderr
# as appropriate.
dup2 r_in 0;
dup2 w_out 1;
dup2 w_err 2;
# Close unused file handles. They're all unused because we duped the
# ones we need. Also, we must close w_in or the child hangs waiting
# for stdin to close.
close r_in; close w_in;
close r_out; close w_out;
close r_err; close w_err;
# Now run the child function, which can use stdin, stdout, and stderr
# normally.
child_fn
)
(
# Parent process. Open the opposite side of each pipe into three new
# file handles.
fdopen w_in "w" \child_in
fdopen r_out "r" \child_out
fdopen r_err "r" \child_err
# Close unused file handles. We don't close the ones we fdopened
# because they are still in play (i.e. fdopen does not dup).
close r_in;
close w_out;
close w_err;
# Return the child's pid, stdin, stdout, and stderr.
next pid child_in child_out child_err
)
)

View file

@ -0,0 +1,72 @@
\test_pipe =
(\next
print "== test_pipe";nl;
### Handy
# Echo entire contents of stream fh to stdout.
\file_print ==
(\fh\next
fgetc fh \ch
long_lt ch 0 next;
putchar ch;
file_print fh next
)
# Show a stream with a descriptive label.
\show_stream =
(\label\fh\next
print "[ ";print label;print ":";nl;
file_print fh;
print "]";nl;
next
)
### Here is a child function to try with spawn.
\child_fn =
(\next
print "Hello from child.";nl;
get_stdin \stdin
show_stream "input from parent" stdin;
print "Good bye from child.";nl;
die "Oops the child had an error!";
next
)
# Spawn the child.
spawn child_fn \pid\child_in\child_out\child_err
# Now we can communicate with the child through its three file handles.
print "Hello from parent, child pid = ";print pid;print ".";nl;
# Say something to the child.
(
# Override print routines for convenience.
\print = (fwrite child_in)
\nl = (print NL)
# Start talking.
print "Hello child, I am your parent!";nl;
print "OK, nice talking with you.";nl;
);
print "The parent is now done talking to the child.";nl;
# Now show the child's stdout and stderr streams.
show_stream "output from child" child_out;
show_stream "error from child" child_err;
# Wait for child to finish.
wait \pid\status
# LATER shift and logical bit operators
# LATER WEXITSTATUS and other wait macros
\status = (long_div status 256)
print "Child ";print pid;print " exited with status ";
print status;print ".";nl;
print "Good bye from parent.";nl;
print "test_pipe completed successfully.";nl;
next
)

View file

@ -0,0 +1 @@
test_pipe;

View file

@ -0,0 +1,31 @@
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

View file

@ -0,0 +1,11 @@
#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” }

26
Task/Fork/Go/fork.go Normal file
View file

@ -0,0 +1,26 @@
package main
import (
"fmt"
"os"
)
func main() {
fmt.Printf("PID: %v\n", os.Getpid())
if len(os.Args) < 2 {
fmt.Println("Done.")
return
}
cp, err := os.StartProcess(os.Args[0], nil,
&os.ProcAttr{Files: []*os.File{nil, os.Stdout}},
)
if err != nil {
fmt.Println(err)
}
// Child process running independently at this point.
// We have its PID and can print it.
fmt.Printf("Child's PID: %v\n", cp.Pid)
if _, err = cp.Wait(); err != nil {
fmt.Println(err)
}
}

View file

@ -0,0 +1,17 @@
println "BEFORE PROCESS"
Process p = Runtime.runtime.exec('''
C:/cygwin/bin/sh -c "
/usr/bin/date +'BEFORE LOOP: %T';
for i in 1 2 3 4 ; do
/usr/bin/sleep 1;
/usr/bin/echo \$i;
done;
/usr/bin/date +'AFTER LOOP: %T'"
''')
p.consumeProcessOutput(System.out, System.err)
(0..<8).each {
Thread.sleep(500)
print '.'
}
p.waitFor()
println "AFTER PROCESS"

View file

@ -0,0 +1,5 @@
import System.Posix.Process
main = do
forkProcess (putStrLn "This is the new process")
putStrLn "This is the original process"

View file

@ -0,0 +1,11 @@
SYSTEM( RUN )
WRITE(Messagebox='?Y', IOStat=ios) "Another Fork?"
IF(ios == 2) ALARM(999) ! quit immediately
! assume this script is stored as 'Fork.hic'
SYSTEM(SHell='Fork.hic')
BEEP("c e g 'c")
WRITE(Messagebox="!") "Waiting ..."
ALARM(999) ! quit immediately

8
Task/Fork/Icon/fork.icon Normal file
View file

@ -0,0 +1,8 @@
procedure main()
if (fork()|runerr(500)) = 0 then
write("child")
else {
delay(1000)
write("parent")
}
end

2
Task/Fork/J/fork.j Normal file
View file

@ -0,0 +1,2 @@
load'dll'
Fork =: (('Error'"_)`('Parent'"_)`)(@.([: >: [: * '/lib/x86_64-linux-gnu/libc-2.19.so __fork > x' cd [: i. 0&[))

38
Task/Fork/Java/fork.java Normal file
View file

@ -0,0 +1,38 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class RFork {
public static void main(String[] args) {
ProcessBuilder pb;
Process pp;
List<String> command;
Map<String, String> env;
BufferedReader ir;
String currentuser;
String line;
try {
command = Arrays.asList("");
pb = new ProcessBuilder(command);
env = pb.environment();
currentuser = env.get("USER");
command = Arrays.asList("ps", "-f", "-U", currentuser);
pb.command(command);
pp = pb.start();
ir = new BufferedReader(new InputStreamReader(pp.getInputStream()));
line = "Output of running " + command.toString() + " is:";
do {
System.out.println(line);
} while ((line = ir.readLine()) != null);
}
catch (IOException iox) {
iox.printStackTrace();
}
return;
}
}

View file

@ -0,0 +1,6 @@
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.")

View file

@ -0,0 +1,26 @@
// 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()
}
}

5
Task/Fork/LFE/fork.lfe Normal file
View file

@ -0,0 +1,5 @@
(defun start ()
(spawn (lambda () (child))))
(defun child ()
(lfe_io:format "This is the new process~n" '()))

View file

@ -0,0 +1,15 @@
local(mydata = 'I am data one')
split_thread => {
loop(2) => {
sleep(2000)
stdoutnl(#mydata)
#mydata = 'Oh, looks like I am in a new thread'
}
}
loop(2) => {
sleep(3000)
stdoutnl(#mydata)
#mydata = 'Aha, I am still in the original thread'
}

10
Task/Fork/Lua/fork.lua Normal file
View file

@ -0,0 +1,10 @@
local posix = require 'posix'
local pid = posix.fork()
if pid == 0 then
print("child process")
elseif pid > 0 then
print("parent process")
else
error("unable to fork")
end

View file

@ -0,0 +1,5 @@
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

View file

@ -0,0 +1,27 @@
/* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
do
pb = ProcessBuilder([String ''])
env = pb.environment()
currentuser = String env.get('USER')
command = Arrays.asList([String 'ps', '-f', '-U', currentuser])
pb.command(command)
pp = pb.start()
ir = BufferedReader(InputStreamReader(pp.getInputStream()))
line = String 'Output of running' command.toString() 'is:'
loop label w_ until line = null
say line
line = ir.readLine()
end w_
catch iox = IOException
iox.printStackTrace()
end
return

4
Task/Fork/NewLISP/fork.l Normal file
View file

@ -0,0 +1,4 @@
(let (pid (fork (println "Hello from child")))
(cond
((nil? pid) (throw-error "Unable to fork"))
('t (wait-pid pid))))

11
Task/Fork/Nim/fork.nim Normal file
View file

@ -0,0 +1,11 @@
import posix
var pid = fork()
if pid < 0:
echo "Error forking a child"
elif pid > 0:
echo "This is the parent process and its child has id ", pid, '.'
# Further parent stuff.
else:
echo "This is the child process."
# Further child stuff.

View file

@ -0,0 +1,6 @@
#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";;

View file

@ -0,0 +1,15 @@
sub=.fork~new
sub~sub
Call syssleep 1
Do 3
Say 'program ' time()
Call syssleep 1
End
::class fork
:: method sub
Reply
Do 6
Say 'subroutine' time()
Call syssleep 1
End

View file

@ -0,0 +1,15 @@
sub=.fork~new
sub~start('start_working')
Call syssleep 1
Do 3
Say 'program ' time()
Call syssleep 1
End
::class fork
:: method start_working
Do 6
Say 'subroutine' time()
Call syssleep 1
End

30
Task/Fork/Oz/fork.oz Normal file
View file

@ -0,0 +1,30 @@
declare
ParentVar1 = "parent data"
ParentVar2
functor RemoteCode
export
result:Result
import QTk at 'x-oz://system/wp/QTk.ozf'
define
Result
%% Show a simple window. When it is closed by the user, set Result.
Window =
{QTk.build
td(action:proc {$} Result = 42 end %% on close
label(text:"In child process: "#ParentVar1))} %% read parent process variable
{Window show}
!ParentVar2 = childData %% write to parent process variable
{Wait Result}
end
%% create a new process on the same machine
RM = {New Remote.manager init(host:localhost)}
%% execute the code encapsulated in the given functor
RemoteModule = {RM apply(RemoteCode $)}
in
%% retrieve data from child process
{Show RemoteModule.result} %% prints 42
%% exit child process
{RM close}
{Show ParentVar2} %% print "childData"

View file

@ -0,0 +1,8 @@
void
foo()
{
if (pari_daemon())
pari_printf("Original\n");
else
pari_printf("Fork\n");
}

9
Task/Fork/PHP/fork.php Normal file
View file

@ -0,0 +1,9 @@
<?php
$pid = pcntl_fork();
if ($pid == 0)
echo "This is the new process\n";
else if ($pid > 0)
echo "This is the original process\n";
else
echo "ERROR: Something went wrong\n";
?>

1
Task/Fork/PL-I/fork.pli Normal file
View file

@ -0,0 +1 @@
ATTACH SOLVE (X) THREAD (T5);

13
Task/Fork/Peri/fork.peri Normal file
View file

@ -0,0 +1,13 @@
###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” }

25
Task/Fork/Perl/fork-1.pl Normal file
View file

@ -0,0 +1,25 @@
FORK:
if ($pid = fork()) {
# parent code
} elsif (defined($pid)) {
setsid; # tells apache to let go of this process and let it run solo
# disconnect ourselves from input, output, and errors
close(STDOUT);
close(STDIN);
close(STDERR);
# re-open to /dev/null to prevent irrelevant warn messages.
open(STDOUT, '>/dev/null');
open(STDIN, '>/dev/null');
open(STDERR, '>>/home/virtual/logs/err.log');
# child code
exit; # important to exit
} elsif($! =~ /emporar/){
warn '[' . localtime() . "] Failed to Fork - Will try again in 10 seconds.\n";
sleep(10);
goto FORK;
} else {
warn '[' . localtime() . "] Unable to fork - $!";
exit(0);
}

9
Task/Fork/Perl/fork-2.pl Normal file
View file

@ -0,0 +1,9 @@
use Proc::Fork;
run_fork {
child {
# child code ...
}
parent {
# parent code ...
}
};

8
Task/Fork/Perl/fork-3.pl Normal file
View file

@ -0,0 +1,8 @@
use Proc::Fork;
# parent code ...
run_fork {
child {
# child code ...
}
};
# parent code continues ...

15
Task/Fork/Perl/fork-4.pl Normal file
View file

@ -0,0 +1,15 @@
use Proc::Fork;
run_fork {
child {
# child code ...
}
parent {
# parent code ...
}
retry {
# retry code ...
}
error {
# error handling ...
}
};

View file

@ -0,0 +1,11 @@
(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>
<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>
<!--

View file

@ -0,0 +1,4 @@
(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>
<!--

View file

@ -0,0 +1,3 @@
(unless (fork) # In child process
(println *Pid) # Print the child's PID
(bye) ) # and terminate

View file

@ -0,0 +1,7 @@
lvars ress;
if sys_fork(false) ->> ress then
;;; parent
printf(ress, 'Child pid = %p\n');
else
printf('In child\n');
endif;

7
Task/Fork/Python/fork.py Normal file
View file

@ -0,0 +1,7 @@
import os
pid = os.fork()
if pid > 0:
# parent code
else:
# child code

16
Task/Fork/R/fork.r Normal file
View file

@ -0,0 +1,16 @@
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))

1
Task/Fork/REXX/fork.rexx Normal file
View file

@ -0,0 +1 @@
child = fork()

View file

@ -0,0 +1,6 @@
#lang racket
(define-values [P _out _in _err]
(subprocess (current-output-port) (current-input-port) (current-error-port)
(find-executable-path "du") "-hs" "/usr/share"))
;; wait for process to end, print messages as long as it runs
(let loop () (unless (sync/timeout 10 P) (printf "Still running...\n") (loop)))

View file

@ -0,0 +1,4 @@
#lang racket
(require ffi/unsafe)
(define fork (get-ffi-obj 'fork #f (_fun -> _int)))
(printf ">>> fork() => ~s\n" (fork))

9
Task/Fork/Raku/fork.raku Normal file
View file

@ -0,0 +1,9 @@
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";
}

6
Task/Fork/Ruby/fork-1.rb Normal file
View file

@ -0,0 +1,6 @@
pid = fork
if pid
# parent code
else
# child code
end

4
Task/Fork/Ruby/fork-2.rb Normal file
View file

@ -0,0 +1,4 @@
fork do
# child code
end
# parent code

View file

@ -0,0 +1,7 @@
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!")

View file

@ -0,0 +1,16 @@
use nix::unistd::{fork, ForkResult};
use std::process::id;
fn main() {
match fork() {
Ok(ForkResult::Parent { child, .. }) => {
println!(
"This is the original process(pid: {}). New child has pid: {}",
id(),
child
);
}
Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()),
Err(_) => println!("Something went wrong."),
}
}

View file

@ -0,0 +1,2 @@
This is the original process(pid: 88637). New child has pid: 88651
This is the new process(pid: 88651).

View file

@ -0,0 +1,16 @@
import java.io.IOException
object Fork extends App {
val builder: ProcessBuilder = new ProcessBuilder()
val currentUser: String = builder.environment.get("USER")
val command: java.util.List[String] = java.util.Arrays.asList("ps", "-f", "-U", currentUser)
builder.command(command)
try {
val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines()
println(s"Output of running $command is:")
while (lines.hasNext) println(lines.next())
}
catch {
case iox: IOException => iox.printStackTrace()
}
}

View file

@ -0,0 +1,14 @@
import java.io.IOException
object Fork extends App {
val command: java.util.List[String] = java.util.Arrays.asList("cmd.exe", "/C", "ECHO.| TIME")
val builder: ProcessBuilder = new ProcessBuilder(command)
try {
val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines()
println(s"Output of running $command is:")
while (lines.hasNext) println(lines.next())
}
catch {
case iox: IOException => iox.printStackTrace()
}
}

View file

@ -0,0 +1,3 @@
var x = 42;
{ x += 1; say x }.fork.wait; # x is 43 here
say x; # but here is still 42

View file

@ -0,0 +1,6 @@
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]]
].

View file

@ -0,0 +1,10 @@
'Here I am' displayNl.
|a|
a := [
(Delay forSeconds: 2) wait .
1 to: 100 do: [ :i | i displayNl ]
] fork.
'Child will start after 2 seconds' displayNl.
"wait to avoid terminating first the parent;
a better way should use semaphores"
(Delay forSeconds: 10) wait.

View file

@ -0,0 +1,3 @@
case Posix.Process.fork () of
SOME pid => print "This is the original process\n"
| NONE => print "This is the new process\n";

View file

@ -0,0 +1,7 @@
| parent
ssx 'R child'
wait 'childevent'
'child is running...' []
'child will end...' []
post 'dieevent'
delay 5000

View file

@ -0,0 +1,4 @@
| child
post 'childevent'
'I am child...' []
wait 'dieevent'

View file

@ -0,0 +1,10 @@
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...

19
Task/Fork/Tcl/fork.tcl Normal file
View file

@ -0,0 +1,19 @@
package require Expect
# or
package require Tclx
for {set i 0} {$i < 100} {incr i} {
set pid [fork]
switch $pid {
-1 {
puts "Fork attempt #$i failed."
}
0 {
puts "I am child process #$i."
exit
}
default {
puts "The parent just spawned child process #$i."
}
}
}

3
Task/Fork/Toka/fork.toka Normal file
View file

@ -0,0 +1,3 @@
needs shell
getpid is-data PID
[ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke

View file

@ -0,0 +1,11 @@
i=0
(while test $i -lt 10; do
sleep 1
echo "Child process"
i=`expr $i + 1`
done) &
while test $i -lt 5; do
sleep 2
echo "Parent process"
i=`expr $i + 1`
done

View file

@ -0,0 +1,5 @@
(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

View file

@ -0,0 +1 @@
(echo "Process 1" >&2 ;sleep 5; echo "1 done" ) | (echo "Process 2";cat;echo "2 done")

View file

@ -0,0 +1,15 @@
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

3
Task/Fork/Wart/fork.wart Normal file
View file

@ -0,0 +1,3 @@
do (fork sleep.1
prn.1)
prn.2

View file

@ -0,0 +1,20 @@
/* fork.wren */
class C {
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")
}

View file

@ -0,0 +1,68 @@
#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;
}

View file

@ -0,0 +1,103 @@
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

View file

@ -0,0 +1,71 @@
; x86_64 linux nasm
%include "/home/james/Desktop/ASM_LIB/Print.asm"
%include "/home/james/Desktop/ASM_LIB/Sleep.asm"
section .data
parent: db "Parent: "
child: db "Child: "
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

9
Task/Fork/XPL0/fork.xpl0 Normal file
View file

@ -0,0 +1,9 @@
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
]

1
Task/Fork/Zkl/fork.zkl Normal file
View file

@ -0,0 +1 @@
zkl: System.cmd("ls &")