我有2个名为file1.c和file2.c中 我想从我的主文件运行file1.c中的多个副本file2.c中如何运行另一个程序的多个副本 - Visual C
回答
检查系统调用fork()和exec()。叉允许复制当前进程及其所有内存。执行调用允许替换为当前进程执行的代码。
基本上,从你的主要过程中,你会叉多次。如果fork的结果为0,则使用子进程的命令行调用exec。
int i;
for (i = 0; i < 10; i++) {
// fork() returns 0 for the child process,
// and the actual pid of the new process for the parent process.
pid_t pid = fork();
if (!pid) {
// This if will be executed only by the child process.
// execvp() first argument is the executable file,
// the second argument is a varargs for each arguments of the command line.
execvp("testsim");
}
}
但是,为了达到这个目的,两个c文件都必须编译成可执行文件。
使用system()
从另一个可执行文件执行可执行文件。
根据你想要多少次运行testsim加入这一行你runsim.c
system("path_to_testsim_executable/testsim_executable_name");
拨打以上电话线。
现在编译.c
文件并运行runsim
可执行文件。
谢谢你能分享你的电子邮件。我想与你分享这个问题。 – Sheri
无法在我的情况下运行 可执行文件名** hello **但是当我运行系统(“hello”); 它输出 你好:没有找到 – Sheri
@Sheri你确定'testsim.c'的可执行文件名是'hello'而不是'a.out'就像你在unix中得到的一样吗?并且您必须提供可执行文件的路径。你不能只在那里写'你好'。我刚刚看到你接受了一个答案。这意味着你已经有了解决方案。在获得解决方案后,我需要另外解释一下吗? – SkrewEverything
您是否知道C文件和程序是不同的东西? –
你是在讨论线程,多进程,还是在runsum中连续多次在testsim中调用函数?没有这些信息,这将很快关闭。 –
@DietrichEpp是的,我知道。 – Sheri