Linux でタスクを実行していますが、うまくいきません。
テキストファイルをパラメーターとして受け取るプログラムがあります。fork()
次に、パラメーターとして受け取ったテキスト ファイルの内容を 1 行ずつ使用して子プロセスを作成し、子プロセスに送信します。子プロセスは行数を数え、受信した行数を親プロセスに返す必要があります。
これは私が今まで持っていたものですが、子プロセスがすべての行を受け取るわけではありません。私のテストでは、9 行のテキスト ファイルを使用しました。親は 9 行を文字列として送信しましたが、子プロセスはそのうちの 2 ~ 3 行しか受信しませんでした。
私は何を間違っていますか?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[80];
char readbuffer[80];
int pid, p[2];
FILE *fp;
int i=0;
if(argc != 2)
{
printf("Syntax: %s [file_name]\n", argv[0]);
return 0;
}
fp = fopen(argv[1], "r");
if(!fp)
{
printf("Error: File '%s' does not exist.\n", argv[1]);
return 0;
}
if(pipe(p) == -1)
{
printf("Error: Creating pipe failed.\n");
exit(0);
}
// creates the child process
if((pid=fork()) == -1)
{
printf("Error: Child process could not be created.\n");
exit(0);
}
/* Main process */
if (pid)
{
// close the read
close(p[0]);
while(fgets(string,sizeof(string),fp) != NULL)
{
write(p[1], string, (strlen(string)+1));
printf("%s\n",string);
}
// close the write
close(p[1]);
wait(0);
}
// child process
else
{
// close the write
close(p[1]);
while(read(p[0],readbuffer, sizeof(readbuffer)) != 0)
{
printf("Received string: %s\n", readbuffer);
}
// close the read
close(p[0]);
}
fclose(fp);
}