【发布时间】:2017-11-03 17:52:14
【问题描述】:
我有一个程序 A,它从标准输入获取两个参数,并根据参数以唯一的代码退出。我正在编写一个程序 B,它使用 fork 和 exec 调用程序 A,并让程序 B 打印出程序 A 退出的代码。出于某种原因,程序 A 似乎没有在 fork 的子进程中获取我通过管道传递给它的数据。我不确定我是否将正确的数据传递给子进程。
有人可以帮帮我吗?谢谢!
这是我的代码:
int program_B(void) {
char var_a[256];
char var_b[256];
int fd[2];
// Read from stdin
char *sendarray[2];
sendarray[0] = var_a;
sendarray[1] = var_b;
if(fgets(var_a, MAXLINE, stdin) == NULL) {
perror("fgets");
exit(1);
}
if(fgets(var_b, MAXLINE, stdin) == NULL) {
perror("fgets");
exit(1);
}
if (pipe(fd) == -1) {
perror("pipe");
exit(1);
}
int pid = fork();
// Child process -- error seems to be here.
if (pid == 0) {
close(fd[1]);
dup2(fd[0], fileno(stdin));
close(fd[0]);
execl("program_A", NULL);
perror("exec");
exit(1);
} else {
close(fd[0]);
write(fd[1], sendarray, 2*sizeof(char*));
close (fd[1]);
int status;
if (wait(&status) != -1) {
if (WIFEXITED(status)) {
printf("%d\n", WEXITSTATUS(status));
} else {
perror("wait");
exit(1);
}
}
}
return 0;
}
【问题讨论】:
-
请注意,不告诉程序它叫什么是一种惯例。您的
execl()行应该是execl("program_A", "program_A", (char *)NULL);。第一个参数是要执行的文件的路径名(当前目录下的programA),第二个是被执行程序的argv[0]中的值。请注意,没有什么可以阻止您使用execl("progam_A", "hypothetical-misnomer", (char *)NULL);给它一个与路径名无关的argv[0]值。