在我的程序的某个时刻,我想运行另一个程序(从标准输入获取参数),其中的参数是我在文本文件中准备的。然后,我想将程序的输出写入另一个文件。
我是 linux、fork 等的新手。试图打破我的头 HOURS 没有成功。我读到我应该将我的输入文件与标准输入相关联,将输出文件与标准输出相关联,类似的东西。
这是我写的代码:
//move on all sub-directories .....
while((indir=readdir(dir))!=NULL)
{
pid_t pid;
DIR *currDir;
struct dirent *cfile;
char *fullpath, *outpath, *outputpath;
//ignore hidden files
if(indir->d_name[0]=='.')
continue;
//create the full path of c file
fullpath=(char*)calloc(strlen(dirpath)+strlen(indir->d_name)+1,sizeof(char));
strcpy(fullpath,dirpath);
fullpath=strcat(fullpath,indir->d_name);
fullpath=strcat(fullpath,"/");
//open current directory
currDir=opendir(fullpath);
//get the c file, ignore hidden files
while((cfile=readdir(currDir))!=NULL)
{
if(cfile->d_name[0]!='.')
break;
}
/*compile c file*/
//child process
if((pid=fork())==0)
{
fullpath=realloc(fullpath, sizeof(char)*(strlen(fullpath)+strlen(cfile->d_name)+1));
outpath=(char*)calloc(strlen(fullpath)+strlen(OUT_NAME)+1,sizeof(char));
strcpy(outpath,fullpath);
strcat(fullpath,cfile->d_name);
strcat(outpath,OUT_NAME);
execl("/usr/bin/gcc", "/usr/bin/gcc", "-o", outpath, fullpath,NULL);
}
else
{
wait(NULL);
}
//create output file path
outputpath=calloc(strlen(fullpath)+strlen(OUTPUTFILE_NAME)+1,sizeof(char));
strcpy(outputpath,fullpath);
strcat(outputpath,OUTPUTFILE_NAME);
inputpath=(char*)calloc(strlen(buff)+1,sizeof(char));
//get input file path from buffer
for(j=0,buffIndex++;buff[buffIndex]!='\n';buffIndex++,j++)
{
inputpath[j]=buff[buffIndex];
}
////Untill here works perfectly////
//child process
if((pid=fork())==0)
{
fullpath=realloc(fullpath, sizeof(char)*(strlen(fullpath)+strlen(OUT_NAME)+1));
strcat(fullpath, OUT_NAME);
//re-open input file and associate it with stdin
freopen(inputpath, "r", stdin);
//re-open output file and associate it with stdout
freopen(outputpath, "w", stdout);
execl(fullpath,inputpath, NULL);
}
else
{
wait(NULL);
}
}
*inputpath 是我为程序输入准备的文件的完整路径。
*outputpath 是我要保存程序输出的文件的完整路径。
我肯定做错了什么,因为我收到以下错误:
/home/aviad/workspace/test/dean/input.txt~: file not recognized: File truncated
collect2: error: ld returned 1 exit status
/home/aviad/workspace/test/jjang/fileoutput.txt: file not recognized: File truncated
collect2: error: ld returned 1 exit status
有什么帮助吗?