【发布时间】:2019-11-26 18:27:27
【问题描述】:
我正在尝试编写一个操作标准输入和输出并将它们重定向到文件的代码,然后使用 execvp(也尝试过其他 exec)运行一个仅使用 printf 和 scanf 的程序,但 execvp 失败..
相关代码:
int pid2 = fork();
if (pid2 == 0) {
int fdInput = open("myinputfile", O_RDONLY);
close(0);
dup(fdInput);
int fdOutput = open("results.txt", O_WRONLY | O_CREAT | O_TRUNC);
close(1);
dup(fdOutput);
char* tmp[]={"...somepath/prog"};
execvp("...somepath/prog", tmp);
}
我的前卫:
int main(){
int x;
scanf("%d",&x);
printf("Hello World! %d",x);
return 0;
}
myinputfile 仅包含 -> 4
我主要尝试了两件事:
- 从 prog 复制代码并将其硬编码到我的代码中,而不是调用 execvp,这工作正常,我可以在 results.txt 中看到“Hello world!4”
- 在终端中手动运行“mypath”,这似乎也可以工作(使用标准 I/O)。
我不明白为什么它不起作用,我尝试了我能想到的一切..
【问题讨论】:
-
char* tmp[]={"...somepath/prog"};这是您的实际代码吗?我假设不是。您能否显示您已编译和运行的实际代码。 “但是 execvp 失败了”。这到底是什么意思?execvp是否返回错误。如果是这样,errno是什么? -
既然你问的是系统调用,你的目标是什么系统?
标签: c io system-calls execvp