fork() を使用してプロセスのリングをセットアップし、リングを介してメッセージを渡すというコーディングの割り当てがあります。さて、この時点で明らかな問題は、最初のプロセスから直接接続された子プロセスにメッセージを渡すことができないことです。(最初にテストとして 1 つのメッセージ パスを実行するだけです)ただし、リングが正しく機能していない可能性もあります。私が使用しているメッセージパッシングテストが本質的にサンプルコードそのままであることを考えると、これが事実であったとしても驚かないでしょうが、リングを形成するコードもそうです...
だから、私の質問は、私のコードで何が間違っているのかを整理するのを手伝ってくれる人はいますか?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int msg[2];
const int MAX = 100;
int main(int argc, char *argv[]) {
int master, i, child, num, pid, ppid, counter, loops;
char buffer[MAX];
num = atoi(argv[1]);
loops = atoi(argv[2]);
counter = 0;
master = (int)getpid();
//check num arguments
if (argc != 4) {
fprintf(stderr, "%s\n", "incorrect # arguments");
}
pipe(msg); //create pipe
dup2(msg[0], STDIN_FILENO); //duplicate pipes
dup2(msg[1], STDOUT_FILENO);
close(msg[0]); //close ends of pipe
close(msg[1]);
//create other processes
for(i=1; i<num; i++) {
pipe(msg); //create new pipe
//create new process
child = fork(); //parent has child id
pid = (int)getpid(); //has own pid
ppid = (int)getppid(); //has parent pid
//if parent, fix output
if(child > 0){
dup2(msg[1], STDOUT_FILENO);
} else {
dup2(msg[0], STDIN_FILENO);
}
close(msg[0]);
close(msg[1]);
if(child){
break;
}
}
//simple output
fprintf(stderr, "process %d with id %d and parent id %d\n", i, pid, ppid);
//message passing
//if master, establish trasnfer
if (pid == master) {
//parent
close(msg[0]); //closes its read end
char buffer[MAX];
fprintf(stderr, "Parent: Waiting for input\n");
while(1) {
scanf("%s", buffer);
if (strcmp(buffer, "exit")==0) {
break;
}
write(msg[1], buffer, MAX);
}
close(msg[1]); //closes it write end
} else {
//child
close(msg[1]); //closes its write end
char buffer[MAX];
fprintf(stderr, "Child: Waiting for pipe\n");
while(read(msg[0], buffer, MAX) > 0) {
fprintf(stderr, "Received: %s\n", buffer);
buffer[0] = '\0';
}
close(msg[0]); //closes its read end
}
//special stuff for master node
if(master == pid){
fprintf(stderr, "%s\n", "i am the master");
//special stuff
} else {
fprintf(stderr, "%s\n", "i am a child");
//nothing really?
}
wait(2); //let all processes finish.
exit(0);
}
講師か TA に聞いてみようと思っていたのですが、2 人とも町を離れ、課題の期限までメールから離れることにしました。これがうまくいかなくても、それで終わりというわけではありませんが、不完全なコーディング課題でコースを開始することは避けたいと思います。