我一直在试图弄清楚如何从文件中循环通过标准输入,然后将其发送到使用 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 sentence\n", word);
}
return 0;
}