親プロセスがパイプを介して2つの子プロセスのそれぞれに文字列の半分(数字)を送信するプロセスツリーを作成することを前提とするプロジェクトに取り組んでいます。数字が出現する回数を計算し、集計を渡します (できれば int の配列の形式で、親に戻します。
私はまだこのことを構築する初期段階にあり、使用に巻き込まれ続けていselect()
ます。現在、プログラムを実行しようとするとSEG_FAULTが発生し、Eclipseにスローすると、ファイル記述子を読み取りに設定しようとした2回目にエラー(EXC_BAD_ACCESS:メモリにアクセスできませんでした)が発生するようですfdセット。
問題がどこにあるのかわかりません。このコードのほとんどは問題とは関係ありませんが、どこかでずさんな間違いを犯した場合に備えて含めました。この問題は bit_count 関数で発生しているようです。ラベルを付けました。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/wait.h>
int bit_count(char *passed, int len);
main(int argc, char *argv[]){
FILE *fp;
fp = fopen(argv[1], "r"); //open the file for reading
if( fp == NULL ) { //file open error
perror ("Error opening file");
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END); //seek to find file size
long int length = ftell(fp); //ftell file length
rewind(fp); //rewind pointer to begin read
char *string = malloc(length+1); //malloc space for the string from the file.
fread(string, 1, length, fp); //begin read
fclose(fp);
if( length < 2){ //make sure string length is greater than 2. Just in case.
printf("File too small. Must have greater than 2 binary digits\n");
return 0;
}
bit_count(string, length); //call bit_count
return 0;
}
int bit_count(char *passed, int len){
int fd1[2], fd2[2]; //file descriptors used for left and right children
fd_set read_set;
fd_set write_set;
struct timeval tv;
tv.tv_sec = 60;
tv.tv_usec = 0;
FD_ZERO(&read_set);
FD_SET(fd1[0], &read_set);
FD_SET(fd2[0], &read_set); //WHERE EXC_BAD_ACCESS OCCURS
pipe(fd1);
pipe(fd2);
pid_t kid = fork();
if(kid == -1) printf("forking failed.");
if (kid == 0){ //first child process
int retval = select(2, &read_set, NULL, NULL, &tv);
if (retval == -1){
printf("Select Error.\n");
}
char *lstring = malloc(len/2+1);
read(fd1[0], lstring, sizeof(lstring));
printf("left %s", lstring);
exit(1);
}
else{ //parent process
pid_t kid2 = fork();
if (kid2 == 0) { //second child process
int retval = select(2, &read_set, NULL, NULL, &tv);
if (retval == -1){
printf("Select Error.\n");
}
char *rstring = malloc(len/2);
read(fd2[0], rstring, sizeof(rstring));
printf("Right %s", rstring);
//execl("child.c", parent);
exit(1);
}
else{
int status;
//create character arrays for first and second half of string
//then copy
char *lstring = malloc(len/2+1);
char *rstring = malloc((len/2)+2);
strncpy(lstring, passed, len/2);
strcpy(rstring, &passed[(len/2)]);
printf("ppp %s", lstring);
write(fd1[1], lstring, sizeof(lstring));
write(fd2[1], rstring, sizeof(rstring));
waitpid(kid, &status, NULL);
waitpid(kid2, &status, NULL);
}
return 0;
}
return 0;
}