【发布时间】:2015-07-27 12:56:51
【问题描述】:
我正在尝试使用管道进行基本的 IPC。我花了几个小时在互联网上搜索,做这做那,阅读 API 文档,最后得到了下面的代码。但它不起作用,正如我所预料的那样。非常感谢让我的代码“工作”的任何帮助。
我刚刚发现使用system 而不是execl 可以使我的程序按预期完美运行。那么当我使用execl 时,这里出了什么问题,而system 函数却没有发生呢?
编辑>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){
int hInPipe[2];
int hOutPipe[2];
FILE *hInFile;
FILE *hOutFile;
char *s;
pipe(hInPipe);
pipe(hOutPipe);
if(fork()){
close(hInPipe[0]);
close(hOutPipe[1]);
hInFile=fdopen(hInPipe[1],"w");
fprintf(hInFile,"2^100\n");
fclose(hInFile);
hOutFile=fdopen(hOutPipe[0],"r");
fscanf(hOutFile,"%ms",&s);
fclose(hOutFile);
printf("%s\n",s);
free(s);
}else{
dup2(hInPipe[0],STDIN_FILENO);
dup2(hOutPipe[1],STDOUT_FILENO);
close(hInPipe[0]);
close(hInPipe[1]);
close(hOutPipe[0]);
close(hOutPipe[1]);
system("bc -q");/*this works*/
/*execl("bc","-q",NULL);*/ /*but this doesn't*/
}
}
【问题讨论】:
-
简化问题。将
bc替换为cat,将fscanf替换为read。并添加错误检查。 -
另外,不要写入未初始化的指针,或者释放它。
-
“它不起作用,正如我所预料的那样”是什么意思?实际发生了什么?你期待什么?
-
@JohnBollinger 我确实写了很多 C,但是我在这种编程方面的经验几乎为零,与操作系统进行了深入的交互。我尝试的示例代码实际上几乎是我现在需要实现的一切。经过数小时的混乱,我认为我得到了 98% 的正确率,但是计算机对于最后 2% 的失误并不是很容易接受。我只需要一个小小的调整就可以完成我的解决方案。
-
@WilliamPursell 那么我的程序的哪一部分出了问题?那里的 fscanf 线对我来说似乎没问题。我用
%ms而不是%s,所以没有写入未初始化的指针。