【发布时间】:2017-11-07 04:55:06
【问题描述】:
我应该创建两个程序(main 和 aux),其中 main 派生一个子程序来执行 aux。父级从用户那里获取输入,直到空行'\n',然后子级执行 aux,这应该将输入打印回来。我能够使用注释代码而不是 execlp() 让它在 main 中工作,但不能让 execlp(aux) 正常工作。任何帮助表示赞赏。
“main.c”
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int fd[2], i;
char line[100], buffer[100];
pipe(fd);
pid_t pid = fork();
if (pid < 0) {
printf("Fork Failed\n");
exit(-1);
}
else if (pid > 0) {
close(fd[0]);
while(fgets(line, sizeof(line), stdin) && line[0] != '\n') {
write(fd[1], line, sizeof(line));
}
close(fd[1]);
}
else {
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
//while(read(fd[0], buffer, sizeof(buffer)))
// printf("> %s", buffer);
execlp("./aux", "aux", (char *)0);
}
return 0;
}
“aux.c”
#include <stdio.h>
#include <stdlib.h>
int main() {
char data[100];
while(fgets(data, sizeof(data), stdin))
printf(">%s\n", data);
return 0;
}
样本输入/输出
this
>this
is a test
>
> test
only prints larger text with random \n
>
>ts larger text with random \n
【问题讨论】:
-
嗨,您正在执行一个带有 exec*() 系列的新图像,它完全替换了原始图像。比如程序文本、堆、栈等。
-
编译所有警告和调试信息:
gcc -Wall -Wextra -g然后使用调试器gdb和strace(1)。添加调试printf。检查execlp是否失败(例如,使用perror("execlp");....) -
您应该在将
fd[0]复制到标准输入后将其关闭。这一次,你侥幸逃脱;你不会总是这样做的。 -
谢谢,伙计们。我能够通过用 strlen(line) 替换 sizeof(line) 来使其工作。我还在你们提到的地方添加了 perror 和 close(fd[0])。