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
,因此当您打印它时,光标将返回到行的开头,并且输出的以下部分将覆盖第一部分。
即使在一个真正的unix上运行,没有\r
使事情复杂化,您也不会得到想要的输出,因为您不允许\n
包含在scanf
的字符串中,并且您没有在输出该字符串的%s
之后添加一个。