【发布时间】:2016-02-06 19:36:51
【问题描述】:
我有一个名为“test”的程序,它执行另一个名为“hello”的程序。收到所需程序的名称后,我的程序似乎在等待更多输入以显示“hello”程序代码。示例代码的sn-p
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> /* for fork */
#include <sys/wait.h> /* for wait */
int main() {
char *temp[] = {NULL,NULL,NULL,NULL};
char buf[BUFSIZ];
char s[256];
while(1) {
printf("type r at next input\n");
fgets(buf, sizeof(buf), stdin);
strtok(buf, "\n");
if((strcmp(buf,"r")) == 0) { //if r typed
printf("run what file : ");
scanf("%s ",s);
pid_t i = fork();
if (i == 0) //we are in child process
{
execv(s,temp);
_exit(1);
}
if (i != 0) { //parent
wait(NULL);
}
}
else
exit(0);
}
}
“hello”程序是...
#include<stdio.h>
main(int argc, char* argv[])
{
printf("\nHello World\n");
}
在 linux 上从 shell 运行的示例是...* 表示我的输入,// 是 cmets
issac@issac-ThinkPad-T440s ~$ ./a.out
type r at next input
*r*
run what file : *hello*
*r* //i cant proceed unless i type a character so i input *r*?
Hello World //after ?additional? input it finally displays the "hello" program code
type r at next input //loops back but program skips my input?
run what file ex ? hello :
我意识到这可能是一个简单的错误,但我无法弄清楚这有什么问题。我意识到跳过输入的最后一部分可能是由于输入缓冲区中有换行符,但更令人困惑的是为什么在执行“hello”后我的程序等待更多输入来显示结果。
【问题讨论】:
-
删除
scanf中的尾随空格。应该是:scanf("%s",s);. -
有效,但程序在执行 hello 后结束,应循环返回并等待更多输入。有什么想法吗?