1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
void exec_cmd(int *to_me, int *from_me, char* paramArray[])
{
dup2(to_me[0], STDIN_FILENO); // Err
dup2(from_me[1], STDOUT_FILENO); // Err
close(to_me[0]); // Err
close(to_me[1]); // Err
close(from_me[0]); // Err
close(from_me[1]); // Err
execvp(paramArray[0], paramArray);
sleep(15) ;
exit(0);
}
int main()
{
while (1)
{
cout << ">";
string command;
string tmp;
int counter;
counter = 0;
getline(cin, command);
tmp =command;
while (tmp.find(" ") != -1)
{
counter++;
tmp = tmp.substr((tmp.find(" ") +1), (tmp.length() - tmp.find(" ") - 1));
//cout << tmp << endl;
}
counter++;
char** paramArray = new char*[counter+1];
int i =0;
while (command.find(" ") != -1)
{
int paramLenght = command.find(" ");
char* param = new char[paramLenght+1];
strcpy(param, command.substr(0, paramLenght).c_str());
paramArray[i] = param;
command = command.substr((paramLenght +1), (command.length() - paramLenght - 1));
i++;
}
int paramLenght = command.length();
char* param = new char[paramLenght+1];
strcpy(param, command.c_str());
paramArray[i] = param;
pid_t pid,pidchild ;
int status ;
int to_cmd[2], from_cmd[2];
int find0A =0;
int findStart;
pipe(to_cmd); // Err
pipe(from_cmd); // Err
printf("I am parent PID %d\n ",getpid()) ;
switch(pid = fork())
{
case (pid_t)-1 :
perror("fatal error... ") ;
exit(2) ;
case (pid_t)0 :
printf(" I am child PID=%d \n ",getpid()) ;
system("echo commande executed by child > /tmp/test/testprogsys.txt");
exec_cmd(to_cmd, from_cmd, paramArray);
default:
char bufferW[10000];
close(from_cmd[1]);
close(to_cmd[0]);
write(to_cmd[1], bufferW, sizeof bufferW); // Err
// Lire le résultat sur from_cmd[1]
//* Ces données sont celles que la commande a envoyé sur la sortie standard
char bufferR[10000];
read(from_cmd[0], bufferR, sizeof bufferR); // Err
string output = bufferR;
int j= 0;
while (j < output.length())
{
findStart = j;
while ((bufferR[j] != 0x0A) && (j != output.length())) j++;
cout << " >>" << output.substr(findStart, (j-findStart)) << endl;
j++;
}
//printf("%s", bufferR);
close(to_cmd[0]); // Err
close(from_cmd[1]); // Err
pidchild = wait(NULL) ; /* attention adresse ! ! ! */
printf(" Death of child PID=%d\n ",pidchild) ;
}
}
return 0;
} |
Partager