私のコードをC#からCに書き直そうとしていますが、少し問題があります。パイプを使用してプロセス間で文字列を送信する
私はtestという名前のファイルがあります。そこには1行のテキストがあります。私はその行を読んで、プロセス間でパイプを介して送信し、それを画面に表示したい。ここで
はコードです:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void
read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
void
write_to_pipe (int file)
{
FILE *stream;
FILE *testfile;
stream = fdopen (file, "w");
testfile = fopen("test.txt", "r");
char *line = NULL;
size_t len = 0;
//ssize_t read;
getline(&line, &len, testfile);
fprintf (stream, "%s", line);
free(line);
fclose(testfile);
fclose (stream);
}
int
main (void)
{
pid_t pid;
int mypipe[2];
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
pid = fork();
if (pid == (pid_t) 0)
{
close (mypipe[1]);
read_from_pipe (mypipe[0]);
return EXIT_SUCCESS;
}
else if (pid < (pid_t) 0)
{
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
close (mypipe[0]);
write_to_pipe (mypipe[1]);
return EXIT_SUCCESS;
}
}
私はこのコードを実行しながら、セグメンテーションエラーになっているようだが。私が紛失しているものはありますか?
どのセグメントがセグメント化エラーを起こしていますか? – Barmar
'getline()'からエラーをチェックする必要があります。エラーが発生した場合、 'line'を割り当てることができないので、印刷しようとするとセグメント化エラーが発生します。 – Barmar
私はプログラムを1行ずつ実行しましたが、実際にはgetlineでブレークします。私はCにうまく対応していませんが、どうすればこの問題を回避できますか? – Januszoff