2010-04-06 48 views
2

我在c languge中创建了一个小程序。该程序使用fork()函数创建了一些子程序。创建的程序的数量作为第一个参数控制台。我希望有人帮助我将这个程序从c转换为bash脚本。将程序从c转换为bash脚本

/* 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); 
     }      
    } 
} 
+3

你到目前为止有什么? – mdm 2010-04-06 13:45:52

+0

如果你丢弃代码,那么它并不重要,但是对fork()返回的检查看起来不正确,应该是子节点的'(pid == 0)'。 – Hasturkun 2010-04-06 14:12:20

回答

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 
+1

你知道'seq'不是很便携。或者至少它不在我的系统上。 :-) – 2010-04-06 14:07:23

+1

@Donal Fellows - 'seq'是GNU核心工具的一部分。 'bash'是GNU shell。同样的论点可以用于'tr',或者去任何安装了bash的系统作为附加组件。我同意它的良好实践来测试任何你打算打电话和执行的可执行文件,或者由于它缺失而失败,但大多数默认情况下封装GNU的现代发行版一直提供'seq'。 – 2010-04-06 14:19:29

+0

你实际上有些误解,除非你只考虑Linux。还有其他许多Unix,GNU核心实用程序并没有那么广泛。 'bash'更常见。 (例如:OSX Leopard。) – 2010-04-06 14:49:31

2

叉()是一个系统调用所使用的编译程序创建另一种方法。在shell脚本中不需要它。你可以简单地使用

myscript.sh & 

在脚本中启动一个新的进程。