how to call a program in another main() function
May 13, 2009 at 11:12am UTC
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 May 13, 2009 at 11:13am UTC
May 13, 2009 at 3:24pm UTC
What OS are you using?
Do you want sim to run concurrently or consecutively?
...
May 13, 2009 at 3:43pm UTC
linux
I have no idea about whether concurrent or consecutive, maybe the second
which one do you think could realize the loop?
THanks
May 13, 2009 at 4:22pm UTC
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.
May 13, 2009 at 5:02pm UTC
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;
}
May 13, 2009 at 5:17pm UTC
That's fine.
May 13, 2009 at 5:57pm UTC
thanks!
Topic archived. No new replies allowed.