Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stop Forking

Status
Not open for further replies.

amarg

Programmer
Nov 19, 2002
106
0
0
IN
Hi,

Following code is doing the fork of 200 process, and run some command on it. It's doing the fork for all 200 processes in once. I need 50 Processes to be forked, and then is any finish start new one. How I can do it?

#include <unistd.h>

pid_t pid;
long forking_counter;
int i_seq_no;
int i_arr_idx;
int i_exec_idx;

int process_count = 0;

typedef struct st_pro {
int p_no;
pid_t p_id;
int status;
};
struct st_pro pro_array[200];

void call_func(pid_t p)
{
system("./mysh");
}


int main()
{
i_arr_idx = 0;
i_exec_idx = i_arr_idx;
forking_counter = 2;
pid = getpid();

// printf("Amar: forking_counter = [%d], pid = [%d], i_seq_no = [%d]\n", forking_counter, pid, i_seq_no);

while((pid!=0) && (forking_counter <=200))
{
i_arr_idx++;
sleep(0);
pid = fork();
if (pid == -1)
{
printf("Amar: Unable to fork the new process\n");
exit(0);
}
if(pid != 0)
{
pro_array[i_arr_idx].p_no = forking_counter;
pro_array[i_arr_idx].p_id = pid;
forking_counter++;
// printf("Amar: forking_counter = [%d], pid = [%d]\n", forking_counter, pid);
for(int i = 0; i < forking_counter; i++) {
printf("Amar: [%d][%d]\n", i, pro_array[i_arr_idx].p_id);
}
}
else
i_exec_idx = i_arr_idx;
}

call_func(pid);


return 0;
}

 
After creating 50, you use the wait() system call to wait for a child to exit. For each successful call to wait(), you can create one new process using fork(), until you reach your limit.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top