Fork: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Using libheader)
(Added Java example)
Line 42: Line 42:
c(fork).
c(fork).
fork:start().
fork:start().

=={{header|Java}}==
public class Threads{
public static void main(String[] args){
Thread otherProgram =
new Thread(){ //anonymous class definition
//this overridden method counts once every second up to five
public void run(){
for(int i= 0; i <= 5; i++){
System.out.println("otherProgram: " + i);
try{
Thread.sleep(1000); //pause this thread for a second
}catch(InterruptedException e){
System.err.println(e.getMessage());
}
}
}
};
otherProgram.start(); //calling .run() will not run it in a new thread
for(int i= 0; i <= 5; i++){
System.out.println("this: " + i);
try{
Thread.sleep(1000); //pause this thread for a second
}catch(InterruptedException e){
System.err.println(e.getMessage());
}
}
}
}
Output:
this: 0
otherProgram: 0
this: 1
otherProgram: 1
this: 2
otherProgram: 2
this: 3
otherProgram: 3
otherProgram: 4
this: 4
otherProgram: 5
this: 5


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 20:22, 7 February 2008

Task
Fork
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to spawn a new process which can run simultaneously with, and independently of, the original parent process.

C

Compiler: gcc

Library: POSIX
#include<stdio.h>
#include<unistd.h>

int main(void)
{
  pid_t pid;

  if((pid=fork())==0) {
    printf("This is new process\n");
  } else if(pid>0) {
    printf("This is the original process\n");
  } else {
    printf("ERROR: Something went wrong\n");
  }

  return 0;
}

Erlang

-module(fork).
-export([start/0]).

start() ->
    spawn(fun child/0),
    io:format("This is the original process~n").

child() ->
    io:format("This is the new process~n").

Then you can compile your code and execute it:

c(fork).
fork:start().

Java

public class Threads{
   public static void main(String[] args){
      Thread otherProgram = 
            new Thread(){ //anonymous class definition
               //this overridden method counts once every second up to five
               public void run(){
                  for(int i= 0; i <= 5; i++){
                     System.out.println("otherProgram: " + i);
                     try{
                        Thread.sleep(1000); //pause this thread for a second
                     }catch(InterruptedException e){
                        System.err.println(e.getMessage());
                     }
                  }
               }
            };
      otherProgram.start(); //calling .run() will not run it in a new thread
      for(int i= 0; i <= 5; i++){
         System.out.println("this: " + i);
         try{
            Thread.sleep(1000); //pause this thread for a second
         }catch(InterruptedException e){
            System.err.println(e.getMessage());
         }
      }
   }
}

Output:

this: 0
otherProgram: 0
this: 1
otherProgram: 1
this: 2
otherProgram: 2
this: 3
otherProgram: 3
otherProgram: 4
this: 4
otherProgram: 5
this: 5

Perl

Interpreter: Perl 5.x

In the child code, you may have to re-open database handles and such.

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);
}

Obviously you could do a Fork in a lot less lines, but this code covers all the bases

Pop11

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

Python

Interpreter: Python 2.5

import os

pid = os.fork()
if pid > 0:
 # parent code
else:
 # child code

Toka

needs shell
getpid is-data PID
[ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke