将程序从c转换为bash脚本

时间:2021-11-25 00:11:26

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.

我用c语言创建了一个小程序。这个程序用fork()函数创建了一些子进程。创建的procceses数量作为控制台的第一个参数给出。我希望有人帮我将这个程序从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);
        }                    
    }
}

2 个解决方案

#1


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

#2


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

fork()是一个系统调用,由编译程序用来创建另一个进程。在shell脚本中没有必要。你可以简单地使用

myscript.sh &

in your script to start a new process.

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

#1


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

#2


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

fork()是一个系统调用,由编译程序用来创建另一个进程。在shell脚本中没有必要。你可以简单地使用

myscript.sh &

in your script to start a new process.

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