childc.exe
程序是这样的:
#include<stdio.h>
#include<windows.h>
int main()
{
printf("this is apple pie\n");
return 0;
}
主程序调用fork()
,然后调用execl()
来处理childc.exe
。代码如下:
#include <stdio.h>
#include<windows.h>
#include<unistd.h>
int main()
{
int fd[2];
if(pipe(fd)==-1)
{
printf("pipe failed\n");
exit(1);
}
pid_t pid=fork();
if(!pid)
{
dup2(fd[1],1);
close(fd[0]);
execl("childc.exe","childc.exe",NULL);
}
dup2(fd[0],0);
close(fd[1]);
char line[100];
scanf("%[^\n]",line);
printf("the line is:%sand this is the end\n",line);
return 0;
}
我希望得到这样的输出:
the line is: this is apple pie
and this is the end
但实际输出是:
and this is the end apple pie
请帮忙。
最佳答案
看起来像 unix 代码,除了 .exe
和 <windows.h>
.在 cygwin 中运行这个?
问题似乎是子进程使用 Windows 样式的 CRLF 行终止符打印其输出,而父进程的 scanf
正在阅读 LF 但不包括它,因为你说 %[^\n]
.
这会得到一个包含 \r
的字符串后面没有 \n
, 所以当你打印它时,光标会回到行首,输出的后续部分会覆盖第一部分。
即使在没有 \r
的真实 unix 上运行使事情复杂化,你不会得到你想要的输出,因为你不允许 \n
包含在 scanf
中'ed 字符串,但您没有在 %s
之后添加一个输出那个字符串。
关于c - 管道后打印顺序困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994729/