tags:

views:

87

answers:

2

Hello! I have created a small program in c languge.This program creates some child procceses in with the fork() function.The amount of the procceses that are created is given as the first argument of the console. I would like someone to help me convert this program from c to bash script.

/* The first argument is the amount of the procceses to be created*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
main(int argc, char **argv)
{
    int  pid,i;
    int pnumber;
    pnumber=atoi(argv[1]);//Converting the first arg to int so i can put in for loop
    for(i=1;i<=pnumber;i++){
        pid=fork();// Creating the child procceses with fork

        if(pid!=0)  { //The child procces prints its id and then exit
             printf("The id the created proccess is:%d  and it is a child proccess \n",pid);
             printf("RETURN\n");
             exit(1);
        }                    
    }
}
+2  A: 
#!/bin/bash

if [ -z $1 ]; then
   echo "I am child"
   exit 0
fi

for i in `seq $1`; do
    $0 &
    echo "The PID of just spawned child is: $!"
done
pajton
You are aware that `seq` isn't very portable. Or at least it's not on my system. :-)
Donal Fellows
@Donal Fellows - `seq` is part of the GNU core utilities. `bash` is the GNU shell. The same argument could go for `tr`, or go for any system where bash was installed as an add-on. I agree that its good practice to test for any executable that you intend to call and work around or fail due to its absence, but most modern distributions that package GNU by default offer `seq` consistently.
Tim Post
You're actually somewhat misinformed, well, unless you're only considering Linux. There are a number of other Unixes out there, and the GNU core utilities aren't that widely spread. `bash` is far more common. (Case in point: OSX Leopard.)
Donal Fellows
Any nice replacement for `seq`? (other than decrementing arg in a while loop)
pajton
Dennis Williamson
Cool! This `for` would prove a really nice replacement for `seq`.
pajton
+2  A: 

fork() is a system call that is used by compiled programs to create another process. There is no need for it in a shell script. You can simply use

myscript.sh &

in your script to start a new process.

compie