how to call a program in another main() function

I wrote a program (sim) where there is main(int argc,char *argv[]){}
this program could be executed by command line like:
sim 3
and I want to execute this command line in another main()function so as to execute this program several times in a loop
such as
1
2
3
4
for(i=0;i<5;i++)
{
  sim i;
}

how to achieve this goal?
thanks!
Last edited on
closed account (z05DSL3A)
What OS are you using?
Do you want sim to run concurrently or consecutively?
...
linux
I have no idea about whether concurrent or consecutive, maybe the second
which one do you think could realize the loop?

THanks
Google "concurrent" and "consecutive". You probably want the second.

This is a valid use for system().

C
1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <stdlib.h>
...
char cmd[10];
for(i=0;i<5;i++)
{
  sprintf( cmd, "sim %d", i );
  system(cmd);
}


C++
1
2
3
4
5
6
7
8
9
10
#include <cstdlib>
#include <sstream>
using namespace std;
...
for(i=0;i<5;i++)
{
  ostringstream cmd;
  cmd << "sim " << i;
  system(cmd.c_str());
}

Hope this helps.
how about my code
is there any problem with the wait() in the father process

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using namespace std;
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
  pid_t pid;
  cout<<"start"<<endl;
  char str[10];
  for(int i=0;i<5;i++)
  {
  sprintf(str,"%d",i);
  pid=fork();
  switch(pid)
  {
    case -1:
            perror("fork error \n");
            exit(1);
    case 0:
            execl("/home/nanger/Desktop/try/one/sim","sim",str,NULL);
            perror("exec fail");
            exit(1);
    default:
    	    wait(NULL);
            cout<<"complete "<<i<<" times"<<endl;            
  }
  }
  return 0;
}
That's fine.
thanks!
Topic archived. No new replies allowed.