【发布时间】:2011-01-08 02:17:04
【问题描述】:
如何从另一个 C 应用程序中调用两个 C 应用程序?
例如:
pg1.c can be run as ./a.out pg1_args
pg2.c can be run as ./a.out pg2_args
我想写一个可以运行的程序:
./a.out pg1_args pg2_args
结果等价于:
./a.out pg1_args
./a.out pg2_args
./a.out pg1_args
./a.out pg2_args
这里的 pg1 是 svm_scale ,这里的 pg2 是 svm_predict ,两者都取自 libsvm : http://www.csie.ntu.edu.tw/~cjlin/libsvm/
[编辑]
@乔纳森,
我编写这些程序是为了尝试这个概念..
pg1.c
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
FILE *fin;
fin=fopen("pg1file.txt","a");
fprintf(fin,"%s",argv[1]);
fflush(fin);
fclose(fin);
}
pg2.c
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
FILE *fin;
fin=fopen("pg2file.txt","a");
fprintf(fin,"%s",argv[1]);
fflush(fin);
fclose(fin);
}
pg3.c:
#include<stdio.h>
#include<string.h>
int main(int argc,char **argv)
{
int i;
const char *cmd1 = strcat("./pg1 ",argv[1]);
const char *cmd2 = strcat("./pg2 ",argv[2]);
for(i=0;i<4;i++)
{
if (system(cmd1) != 0)
printf("\n error executing pg 1");
if (system(cmd2) != 0)
printf("\n error executing pg 2");
}
}
[root@localhost trinity]# ./a.out first second
Segmentation fault (core dumped)
[root@localhost trinity]#
谁能解释我做错了什么?
【问题讨论】:
-
为什么使用 C 作为包装器?当然,一个简单的 shell 脚本就可以了: while true;做 pg1 pg1_args; pg2 pg2_args;完成
-
strcat 正在注销字符串的末尾,strcat 的第一个参数需要指向一个空间,该空间为您添加到末尾的字符串分配了足够的空间。