我一直在试图找出如何从文件中循环stdin,然后将其发送给使用execl()排序int的子进程。下面的代码之所以有效,是因为它接受文件&对行进行排序,但我没有看到我添加的"句子结束"调试字符串。不知何故,这部分代码被绕过了。我可以使用一些帮助来理解数据流,因为它来自文件,然后被打印到屏幕上。
int main(int argc, char *argv[])
{
pid_t p;
int status;
int fds[2];
FILE *writeToChild;
char word[50];
if(pipe(fds) == -1) {
perror("Error creating pipes");
exit(EXIT_FAILURE);
}
switch(p = fork()) {
case 0: //this is the child process
close(fds[1]); //close the write end of the pipe
execl("/usr/bin/sort", "sort", (char *) 0);
break;
case -1: //failure to fork case
perror("Could not create child");
exit(EXIT_FAILURE);
default: //this is the parent process
close(fds[0]); //close the read end of the pipe
writeToChild = fdopen(fds[1], "w");
wait(&status);
break;
}
while (fscanf(stdin, "%s", word) != EOF) {
//the below isn't being printed. Why?
fprintf(writeToChild, "%s end of sentencen", word);
}
return 0;
}
您的主要问题是您的wait()
在错误的地方。你要等孩子死了才给他写东西。您还有一个次要问题,即没有将管道的读端重定向到sort
进程的标准输入。
你没有关闭孩子的fds[0]
;清洁表明你应该这样做。在等待之前,你确实需要fclose(writeToChild)
;直到父进程关闭到子进程的管道,排序才会停止。
这些变化(以及其他一些变化)导致:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t p;
int status;
int fds[2];
FILE *writeToChild;
char word[50];
if (pipe(fds) == -1)
{
perror("Error creating pipes");
exit(EXIT_FAILURE);
}
switch (p = fork())
{
case 0: //this is the child process
close(fds[1]); //close the write end of the pipe
dup2(fds[0], 0);
close(fds[0]);
execl("/usr/bin/sort", "sort", (char *) 0);
fprintf(stderr, "Failed to exec sortn");
exit(EXIT_FAILURE);
case -1: //failure to fork case
perror("Could not create child");
exit(EXIT_FAILURE);
default: //this is the parent process
close(fds[0]); //close the read end of the pipe
writeToChild = fdopen(fds[1], "w");
break;
}
if (writeToChild != 0)
{
while (fscanf(stdin, "%49s", word) != EOF)
{
//the below isn't being printed. Why?
fprintf(writeToChild, "%s end of sentencen", word);
}
fclose(writeToChild);
}
wait(&status);
return 0;
}