2

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);
        }                    
    }
}
1
  • not that it matters much if you're dropping the code, but the check for fork()'s return looks incorrect, should be (pid==0) for the child. Commented Apr 6, 2010 at 14:12

2 Answers 2

2
#!/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
Sign up to request clarification or add additional context in comments.

6 Comments

You are aware that seq isn't very portable. Or at least it's not on my system. :-)
@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.
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.)
Any nice replacement for seq? (other than decrementing arg in a while loop)
for ((i=0; i<$1; i++)) works in Bash. jot is used in place of seq on BSD systems such as OS X.
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.