/ pipex / pipex / mandatory / pipex_utils.c
pipex_utils.c
 1  /* ************************************************************************** */
 2  /*                                                                            */
 3  /*                                                        :::      ::::::::   */
 4  /*   pipex_utils.c                                      :+:      :+:    :+:   */
 5  /*                                                    +:+ +:+         +:+     */
 6  /*   By: gychoi <gychoi@student.42seoul.kr>         +#+  +:+       +#+        */
 7  /*                                                +#+#+#+#+#+   +#+           */
 8  /*   Created: 2023/01/17 23:22:00 by gychoi            #+#    #+#             */
 9  /*   Updated: 2023/02/02 14:39:33 by gychoi           ###   ########.fr       */
10  /*                                                                            */
11  /* ************************************************************************** */
12  
13  #include "pipex.h"
14  
15  void	px_error(char *str, char *file, int exitcode)
16  {
17  	if (file)
18  	{
19  		ft_putstr_fd(file, STDERR_FILENO);
20  		ft_putstr_fd(": ", STDERR_FILENO);
21  		ft_putstr_fd(str, STDERR_FILENO);
22  	}
23  	else
24  		ft_putstr_fd(str, STDERR_FILENO);
25  	exit(exitcode);
26  }
27  
28  int	px_open(char *filename, int flags)
29  {
30  	int	fd;
31  
32  	if (flags == (O_WRONLY | O_CREAT | O_TRUNC))
33  		fd = open(filename, flags, 0644);
34  	else
35  		fd = open(filename, flags);
36  	if (fd == -1)
37  		px_error("Error: open\n", filename, 126);
38  	return (fd);
39  }
40  
41  void	px_close(int fd)
42  {
43  	if (close(fd) == -1)
44  		px_error("Error: close\n", NULL, 1);
45  }
46  
47  void	px_pipe(int *fd)
48  {
49  	if (pipe(fd) == -1)
50  		px_error("Error: pipe\n", NULL, 1);
51  }
52  
53  void	px_dup2(int fd1, int fd2)
54  {
55  	if (dup2(fd1, fd2) == -1)
56  		px_error("Error: dup2\n", NULL, 1);
57  }