Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- int fds[2][2], result;
- // fds[0] parent -> child
- // fds[1] child -> parent
- size_t size;
- char resstring[14];
- for (int i = 0; i < 2; ++i)
- {
- if (pipe(fds[i]) < 0)
- {
- printf("Can\'t open pipe\n");
- exit(-1);
- }
- }
- result = fork();
- if (result < 0)
- {
- printf("Can\'t fork child\n");
- exit(-1);
- }
- else if (result > 0)
- {
- /* Parent process */
- close(fds[0][0]);
- close(fds[1][1]);
- size = write(fds[0][1], "Hello, world!", 14);
- if (size != 14)
- {
- printf("Parent: Can\'t write all string to pipe\n");
- exit(-1);
- }
- size = read(fds[1][0], resstring, 14);
- if (size < 0)
- {
- printf("Parent: Can\'t read string from pipe\n");
- exit(-1);
- }
- printf("Parent: resstring:%s\n", resstring);
- }
- else
- {
- /* Child process */
- close(fds[0][1]);
- close(fds[1][0]);
- size = read(fds[0][0], resstring, 14);
- if (size < 0)
- {
- printf("Child: Can\'t read string from pipe\n");
- exit(-1);
- }
- printf("Child: resstring:%s\n", resstring);
- size = write(fds[1][1], resstring, 14);
- if (size != 14)
- {
- printf("Child: Can\'t write all string to pipe\n");
- exit(-1);
- }
- }
- for(int i = 0; i < 2; ++i){
- close(fds[i][0]);
- close(fds[i][1]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement