I've found some sample code online about how to create a ring with pipes and fork(). I'm to pass messages from one process to another through the pipe.
A process reads in a number from its parent process, but apparently, fscanf() doesn't work as expected. (in main, after creation of pipe in the while loop) The output is not the same.
Any idea what goes wrong? Thanks!
Code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAX 512
void make_trivial_ring(){
int fd[2];
pipe (fd);
dup2(fd[0], STDIN_FILENO);
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
}
void add_new_node(int *pid){
int fd[2];
pipe (fd);
*pid = fork();
if (*pid > 0) dup2(fd[1], STDOUT_FILENO);
else dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
}
int main(int argc, char *argv[ ])
{
int k, i, childpid;
int maxpid, maxnode, maxnum;
make_trivial_ring();
for (i = 1; i < atoi(argv[1]); i++){
add_new_node(&childpid);
if (childpid) break;
}
fprintf(stderr, "123\n");
fscanf(stderr, "%d", &maxpid);
fprintf(stderr, "%d\n", maxpid);
//sleep(5);
exit(0);
}
Output:
Code:
123
1307813
123
1307813
123
1307813