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
| #include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/errno.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
extern int errno;
int main(){
int child = fork();
int p_desc[2];
int err = pipe(p_desc);
if(child > 0){
printf("Processus PERE pid: %d ppid: %d pid_fils: %d \n", getpid(), getppid(), child);
int status;
close(p_desc[0]);
char * msg = malloc(strlen("Je suis ton pere."));
msg = "Je suis ton pere.";
err = write(p_desc[1],msg,strlen(msg));
if(err == -1){
printf("Error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("test1 \n");
wait(&status);
free(msg);
if(WIFEXITED(status)) printf("Mon fils %d s'est correctement terminé.\n", child);
else if(WIFSIGNALED(status)){
printf("Mon fils s'est terminé à cause du signal %d.\n", WTERMSIG(status));
}
printf("test2 \n");
}
else if(child == 0){
printf("Processus FILS pid: %d ppid: %d\n", getpid(), getppid());
close(p_desc[1]);
char * buf = malloc(_POSIX_PIPE_BUF*sizeof(char));
err = read(p_desc[0],buf, strlen(buf));
if(err == -1){
printf("Error: %s \n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("Mon pere m'a dit: %s\n", buf);
free(buf);
exit(EXIT_SUCCESS);
}
else{
perror("Erreur de creation de processus fils !\n");
printf("Error: %s\n", strerror(errno));
}
return 0;
} |
Partager