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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAILLE_LIGNE 32
#define NB_LIGNES 60
// lit x lignes et les place dans le buffer
int read_x_lines(FILE *file, char **buffer, int x)
{
int nb_lignes_lues = 0;
int i=0;
while((fgets(buffer,TAILLE_LIGNE,file))!= NULL && i<x)
{
nb_lignes_lues++;
i++;
}
/*
for(i=0;i<NB_LIGNES;i++)
printf(" %s \n",buffer[i]);*/
return nb_lignes_lues;
}
// crée un fils en lui transmettant une chaine de caractère qu'il devra afficher et écrire dans le fichier "filename"
int create_new_child(char *text, char *filename)
{
pid_t fils;
printf(" Creation du fils \n");
fils = fork();
switch(fils)
{
case -1 :
{
perror(" fork ");
exit(1);
}
case 0 :
{
printf(" %s \n",text);
FILE *fd = fopen(filename,"r");
if(fwrite(text,sizeof(text), TAILLE_LIGNE, fd) == -1)
perror(" write ");
exit(0);
}
default :
{
wait((int*)0);
return fils;
}
}
}
int *read_file_and_create_childs(char *srcname, char *dstname, int x, int nbprocs)
{
int i = 0;
int p[12];
int nbll;
char **buffer;
buffer = (char **)malloc(NB_LIGNES*sizeof(char *));
for (i=0; i<NB_LIGNES; i++)
{
buffer[i] = (char*)malloc( sizeof(char*) * TAILLE_LIGNE);
}
FILE *file = fopen(srcname,"r");
nbll = read_x_lines(file, buffer, srcname);
while(i<x)
{
p[i] = create_new_child(buffer, dstname);
i++;
}
return p;
}
int main(int argc, char **argv) // argv[1] = n, argv[2] = fichier_source, argv[3] = fichier_destination
{
pid_t pid;
int *PID;
PID = read_file_and_create_childs(argv[2], argv[3], argv[1], 1);
exit(0);
} |
Partager