Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <memory.h>
- #include <sys/fcntl.h>
- #define CHILD_NUMBER 1
- /* Creates a vector of CHILD_NUMBER pipes. */
- void create_pipe(int fd[2]) {
- /* In case of an error exits with code -1 */
- if (pipe(fd) == -1) {
- printf("Error while attempting to create pipe.\n");
- exit(-1);
- }
- }
- /* Creates CHILD_NUMBER child processes, stores each pid in the pids array and returns each child process id. */
- int babymaker() {
- int i;
- pid_t p;
- for (i = 0; i < CHILD_NUMBER; i++) {
- p = fork();
- /* In case of an error exits with code -1 */
- if (p < 0) {
- printf("Error while attempting to create child process nº %d pipe.\n", i + 1);
- exit(-1);
- }
- /* Child process returns it's id */
- if (p == 0) {
- return i + 1;
- }
- }
- /* Parent process returns 0 */
- return 0;
- }
- void write_value(int fd[2], int value) {
- if (write(fd[1], &value, sizeof(value)) == -1) {
- printf("Error while attempting to write on pipe.\n");
- exit(-1);
- }
- }
- int read_value(int fd[2], int *value) {
- int status = (int) read(fd[0], value, sizeof(value));
- if (status == -1) {
- printf("Error while attempting to read from pipe.\n");
- exit(-1);
- }
- return status;
- }
- void close_file_descriptor(int fd[2], int i) {
- if (close(fd[i]) == -1) {
- /* In case of an error exits with value -1 */
- printf("Error while attempting to close file descriptor.\n");
- exit(-1);
- }
- }
- int main() {
- int id, number, res, parent_to_child[2], child_to_parent[2];
- create_pipe(parent_to_child);
- create_pipe(child_to_parent);
- id = babymaker();
- if (id != 0) {
- close_file_descriptor(parent_to_child,1);
- close_file_descriptor(child_to_parent,0);
- dup2(child_to_parent[1], fileno(stdin));
- execlp("./ex15_simples", "./ex15_simples", (char *) NULL);
- dup2(child_to_parent[0], fileno(stdout));
- close_file_descriptor(parent_to_child,0);
- close_file_descriptor(child_to_parent,1);
- } else {
- close_file_descriptor(parent_to_child,0);
- close_file_descriptor(child_to_parent,1);
- scanf("%d\n", &number);
- write_value(parent_to_child, number);
- close_file_descriptor(parent_to_child,1);
- read_value(child_to_parent,&res);
- close_file_descriptor(child_to_parent,0);
- printf("%d",res);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement