1

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

助けてください。

4

2 に答える 2

2

.exeとを除いて、UNIX コードのように見え<windows.h>ます。これをcygwinで実行していますか?

問題は、子プロセスが Windows スタイルの CRLF ライン ターミネータを使用して出力を出力していることと、親プロセスscanfが LF まで読み取っているが、あなたが言ったためにそれを含めていないことです%[^\n]

\rこれにより、後ろに が続かない文字列が得\nられるため、それを印刷すると、カーソルが行の先頭に戻り、出力の次の部分が最初の部分を上書きします。

\r事態を複雑にするためにno を使用して実際の UNIX 上で実行したとしても、必要な出力が得られません\n。.scanf%s

于 2013-06-08T00:52:10.427 に答える
1

Wumpus Q. Wumbley が Windows CRLF 改行と Unix/Linux LF 改行に関して言及したような、プラットフォーム固有の問題を回避するgetline代わりに使用してみます。scanf

char *line = NULL;
getline(&line, NULL, stdin)
printf("the line is:%sand this is the end\n",line);
于 2013-06-08T01:10:50.813 に答える