我有一个编码任务,其中我要使用 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);
}
我会问我的导师或助教,但他们都决定出城,远离电子邮件,直到作业到期。如果我不能让这个工作,它不是世界末日,但我想避免以不完整的编码作业开始课程。