Răsfoiți Sursa

:sparkles: Ajout fonction redirect_fd

Loquicom 6 ani în urmă
părinte
comite
2cef3dd2ac
3 a modificat fișierele cu 41 adăugiri și 4 ștergeri
  1. 25 1
      error.c
  2. 12 2
      error.h
  3. 4 1
      mysh.c

+ 25 - 1
error.c

@@ -7,6 +7,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <unistd.h>
 #include "error.h"
 
 /* --- Extern --- */
@@ -21,4 +22,27 @@ char* serrlib[] = {
     "Command incorrect",
     "Analyse wildcard impossible",
     "Echec ajout wildcard dans argv"
-};
+};
+
+/* --- Fonctions publiques --- */
+int redirect_fd(int fd1, int fd2){
+    int tmpfd;
+    //On duplique le 1er fd
+    tmpfd = dup(fd1);
+    if(tmpfd == ERR){
+        addperror("Erreur pendant la duplication");
+        return ERR;
+    }
+    //On fait en sorte que fd1 soit lié au fichier de fd2
+    if(dup2(fd2, fd1) == ERR){
+        addperror("Erreur pendant le changement de fd");
+        return ERR;
+    }
+    //On ferme l'ancien fd2
+    if(close(fd2) == ERR){
+        addperror("Erreur pendant la fermeture de fd2");
+        return ERR;
+    }
+    //On retourne le nouveau fd de fd1
+    return tmpfd;
+}

+ 12 - 2
error.h

@@ -9,18 +9,19 @@
 #define ERROR_H
 
 #include <stdio.h>
-#include <errno.h>
 
 
 /* --- Macro --- */
 #define serror(str) fprintf(stderr, str" : %s\n", serrlib[serrno])
 #define strserror(index) serrlib[index]
 #define adderror(str) fprintf(stderr, "Erreur dans le fichier "__FILE__" ligne %d, "str"\n", __LINE__)
-#define addperror(str) fprintf(stderr, "Erreur dans le fichier "__FILE__" ligne %d, "str" : %s\n", __LINE__, strerror(errno))
+#define addperror(str) fprintf(stderr, "Erreur dans le fichier "__FILE__" ligne %d, ", __LINE__); perror(str" ")
 #define addserror(str) fprintf(stderr, "Erreur dans le fichier "__FILE__" ligne %d, "str" : %s\n", __LINE__, strserror(serrno))
 
 /* --- Constantes Generales --- */
 #define ERR -1
+#define FAIL 0
+#define SUCCESS 1
 
 /* --- Constantes Erreurs --- */
 #define SEBADEND 1
@@ -37,5 +38,14 @@ extern int errno;
 extern int serrno; //Shell Errno
 extern char* serrlib[];
 
+/* --- Fonctions --- */
+/**
+ * Change un fd par la valeur d'un autre fd
+ * @param int fd accueil
+ * @param int fd source
+ * @return int Le nouveau fd du fichier qui avait le fd d'accueil
+ */
+int redirect_fd(int, int);
+
 #endif /* ERROR_H */
 

+ 4 - 1
mysh.c

@@ -13,6 +13,9 @@
 #include "parser.h"
 #include "mysh.h"
 
+#include <sys/types.h>
+#include <sys/stat.h>
+
 /* --- Fonctions privées --- */
 void test_write() {
     char* a = "azerty\n";
@@ -40,7 +43,7 @@ void show_current_dir(const char* before, const char* after) {
 
 /* --- Main --- */
 int main(int argc, char* argv[]) {
-
+    
     CommandTab ct;
     char str[BUFFER_SIZE];
     int a;