I just need some help understanding this problem. Pointing in the right directio
ID: 665573 • Letter: I
Question
I just need some help understanding this problem. Pointing in the right direction would be very helpful.
C++ in a UNIX Environment
Part1 Create a one-directional ring of pipe for N processes (N 1)
Part2 Create a one-directional ring of pipe for N threads
Part3 Create a one-directional ring of socket for N hosts (or all in one).
You may run N processes in one host.
Each process has two designated ports - one for sending and the other for receiving.
Each program for each process will be run with an argument telling which process (Nth process)
You may assume that each process has a table of process with 2 ports as following:
Process i
IP address
Port# to send
Port# to receive
0
127.0.0.1
9000
9001
1
127.0.0.1
9100
9101
2
127.0.0.1
9200
9201
and so on
When N processes (or threads) in a ring are up and ready, Process 0 sends a message to be received by Process 1, and so on, to back to Process 0 and done. Whenever a process sends or receives a message, it prints its process # (N), "the message", and "sent" or "received".
Process i
IP address
Port# to send
Port# to receive
0
127.0.0.1
9000
9001
1
127.0.0.1
9100
9101
2
127.0.0.1
9200
9201
and so on
Explanation / Answer
Part 1:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
void main(int argc, char *argv[ ])
{
int i;
int cpid;
int prcs;
int fd[2];
int error;
/* check command line for a valid number of processes to generate */
if ( (argc != 2) || ((prcs = atoi (argv[1])) <= 0) ) {
fprintf (stderror, "Usage: %s prcs ", argv[0]);
exit(1);
}
/* connect std input to std output via a pipe */
if (pipe (fd) == -1) {
perror("Could not create pipe");
exit(1);
}
if ((dup2(fd[0], STDIN_FILENO) == -1) ||
(dup2(fd[1], STDOUT_FILENO) == -1)) {
perror("Could not dup pipes");
exit(1);
}
if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) {
perror("Could not close extra descriptors");
exit(1);
}
/* create the remaining processes with their connecting pipes */
for (i = 1; i < prcs; i++) {
if (pipe (fd) == -1) {
fprintf(stderror,"Could not create pipe %d: %s ",
i, strerror(errno));
exit(1);
}
if ((cpid = fork()) == -1) {
fprintf(stderror, "Could not create child %d: %s ",
i, strerror(errno));
exit(1);
}
if (cpid > 0) /* for parent process, reassign stdout */
error = dup2(fd[1], STDOUT_FILENO);
else
error = dup2(fd[0], STDIN_FILENO);
if (error == -1) {
fprintf(stderror, "Could not dup pipes for iteration %d: %s ",
i, strerror(errno));
exit(1);
}
if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) {
fprintf(stderror, "Could not close extra descriptors %d: %s ",
i, strerror(errno));
exit(1);
}
if (cpid)
break;
}
exit (0);
}