Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6. #include <memory.h>
  7. #include <sys/fcntl.h>
  8.  
  9. #define CHILD_NUMBER 1
  10.  
  11. /* Creates a vector of CHILD_NUMBER pipes. */
  12. void create_pipe(int fd[2]) {
  13. /* In case of an error exits with code -1 */
  14. if (pipe(fd) == -1) {
  15. printf("Error while attempting to create pipe.\n");
  16. exit(-1);
  17. }
  18. }
  19.  
  20. /* Creates CHILD_NUMBER child processes, stores each pid in the pids array and returns each child process id. */
  21. int babymaker() {
  22. int i;
  23. pid_t p;
  24.  
  25. for (i = 0; i < CHILD_NUMBER; i++) {
  26. p = fork();
  27. /* In case of an error exits with code -1 */
  28. if (p < 0) {
  29. printf("Error while attempting to create child process nº %d pipe.\n", i + 1);
  30. exit(-1);
  31. }
  32. /* Child process returns it's id */
  33. if (p == 0) {
  34. return i + 1;
  35. }
  36. }
  37. /* Parent process returns 0 */
  38. return 0;
  39. }
  40.  
  41. void write_value(int fd[2], int value) {
  42. if (write(fd[1], &value, sizeof(value)) == -1) {
  43. printf("Error while attempting to write on pipe.\n");
  44. exit(-1);
  45. }
  46. }
  47.  
  48. int read_value(int fd[2], int *value) {
  49. int status = (int) read(fd[0], value, sizeof(value));
  50. if (status == -1) {
  51. printf("Error while attempting to read from pipe.\n");
  52. exit(-1);
  53. }
  54. return status;
  55. }
  56.  
  57. void close_file_descriptor(int fd[2], int i) {
  58. if (close(fd[i]) == -1) {
  59. /* In case of an error exits with value -1 */
  60. printf("Error while attempting to close file descriptor.\n");
  61. exit(-1);
  62. }
  63.  
  64. }
  65. int main() {
  66. int id, number, res, parent_to_child[2], child_to_parent[2];
  67.  
  68. create_pipe(parent_to_child);
  69. create_pipe(child_to_parent);
  70.  
  71. id = babymaker();
  72.  
  73. if (id != 0) {
  74. close_file_descriptor(parent_to_child,1);
  75. close_file_descriptor(child_to_parent,0);
  76. dup2(child_to_parent[1], fileno(stdin));
  77. execlp("./ex15_simples", "./ex15_simples", (char *) NULL);
  78. dup2(child_to_parent[0], fileno(stdout));
  79. close_file_descriptor(parent_to_child,0);
  80. close_file_descriptor(child_to_parent,1);
  81. } else {
  82. close_file_descriptor(parent_to_child,0);
  83. close_file_descriptor(child_to_parent,1);
  84. scanf("%d\n", &number);
  85. write_value(parent_to_child, number);
  86. close_file_descriptor(parent_to_child,1);
  87. read_value(child_to_parent,&res);
  88. close_file_descriptor(child_to_parent,0);
  89. printf("%d",res);
  90. }
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement