Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <sys/types.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <semaphore.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #define BUF_SIZE 512
- const char* read_sem_name = "read_semaphore";
- const char* write_sem_name = "write_semaphore";
- const char* child_name = "/home/zakhar/Documents/C/Pipe/Client";
- sem_t* open_sem(const char* sem_name, unsigned int value)
- {
- sem_t* sem = sem_open(sem_name, O_CREAT, S_IRWXO | S_IRWXU, value); // other processes have write and read permission
- if (sem == SEM_FAILED)
- {
- fprintf(stderr, "Can't create a semaphore\n");
- return NULL;
- }
- return sem;
- }
- int main(int argc, char** argv)
- {
- sem_t* read_sem = open_sem(read_sem_name, 0);
- sem_t* write_sem = open_sem(write_sem_name, 1);
- int pipefd[2];
- if (pipe(pipefd) == -1)
- {
- fprintf(stderr, "Can't make a pipe\n");
- exit(EXIT_FAILURE);
- }
- char string[BUF_SIZE];
- char** args = malloc(sizeof(char*) * 2);
- args[0] = malloc(sizeof(char) * (strlen(child_name) + 1));
- strncpy(args[0], child_name, strlen(child_name) + 1);
- args[1] = NULL;
- pid_t pid = fork();
- if (pid == -1)
- {
- fprintf(stderr, "Can't create a child process\n");
- close(pipefd[1]);
- close(pipefd[0]);
- sem_close(read_sem);
- sem_close(write_sem);
- sem_unlink(write_sem_name);
- sem_unlink(read_sem_name);
- exit(EXIT_FAILURE);
- }
- else
- {
- if (pid == 0)
- {
- close(pipefd[1]);
- if (dup2(pipefd[0], 0) == -1)
- {
- fprintf(stderr, "Failed to dup read end\n");
- exit(EXIT_FAILURE);
- }
- close(pipefd[0]);
- if (execvp(child_name, args) == -1)
- {
- fprintf(stderr, "Execvp error!\n");
- exit(EXIT_FAILURE);
- }
- }
- }
- close(pipefd[0]);
- while (1)
- {
- sem_wait(write_sem);
- fgets(string, BUF_SIZE, stdin);
- if (*string == '\0' || *string == '\n' || *string == '\r')
- {
- kill(pid, SIGTERM);
- break;
- }
- write(pipefd[1], string, BUF_SIZE);
- sem_post(read_sem);
- }
- close(pipefd[1]);
- sem_close(read_sem);
- sem_close(write_sem);
- sem_unlink(write_sem_name);
- sem_unlink(read_sem_name);
- free(args[0]);
- free(args);
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement