Académique Documents
Professionnel Documents
Culture Documents
Objectifs :
Création et communication entre processus
1. #include<stdio.h>
2. #include<sys/types.h>
3. #include<unistd.h>
4.
5. int main(int argc, char **argv) {
6. int p1, p2, p3;
7. p1 = fork();
8. p2 = getpid();
9. p3 = getppid();
10. printf("p1=%d - p2=%d - p3=%d\n",p1,p2,p3);
11. return 0;
12. }
1.2
1. #include<stdio.h>
2. #include<sys/types.h>
3. #include<unistd.h>
4.
5. int main(int argc, char **argv) {
6. int p1, p2, p3;
7. p2 = getpid();
8. p3 = getppid();
9. p1 = fork();
10. printf("p1=%d - p2=%d - p3=%d\n", p1, p2, p3);
11. return 0;
12. }
1.3
1. #include<stdio.h>
2. #include<sys/types.h>
1 TP N°3
3. #include<unistd.h>
4.
5. int main(int argc, char **argv) {
6. int pid;
7. int x = 2;
8. printf("x=%d\n",x);
9. pid = fork();
10. x = x+1;
11. printf("x=%d\n",x);
12. if (pid != 0) {
13. waitpid(pid, 0, 0);
14. }
15. return 0;
16. }
printf("%s\n", argv[1]);
return 0;
}
2.2 Ecrire un programme prog1 qui crée un processus fils qui exécute print avec l’argument salut. On
utilisera la fonction execl.
2 TP N°3
Réponse :
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, char const *argv[]) {
pid_t pid;
if ((pid=fork()) < 0)
{
perror("Erreur de fork");
}
else if(pid == 0)
{
if(execl("chemin","TP3_EX3_a","Salut",(char *) NULL))
{
perror("execl error");
}
}
wait(NULL);
return 0;
}
3 TP N°3
Exercice 4 : La fonction wait()
Ecrire un programme qui crée 2 processus, l’un faisant la commande ls -l, l’autre ps -l. Le père devra
attendre la fin de ses deux fils et afficher quel a été le premier processus à terminer.
Réponse :
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[]) {
pid_t pid1,pid2;
int status;
if ((pid1=fork()) < 0)
{ perror("la création d'un processus fils a échoué");
exit(1);
}
else if(pid1 > 0)
printf("Processus créé avec Pid : %d\n",pid1);
if (pid1 == 0)
{
execlp("ls", "ls", "-l",(char *) NULL);
perror("Erreur d'exécution de execlp");
exit(-1);
}
if ((pid2=fork()) < 0)
{ perror("la création d'un processus fils a échoué");
exit(-1);
}
else if (pid2 > 0)
{
printf("Processus créé avec Pid : %d\n",pid2 );
}
if (pid2 == 0)
{
execlp("ps", "ps", "-l",NULL);
perror("Erreur d'exécution de execlp");
exit(-1);
}
else
{
wait(&status);
printf("Premier processus à terminer: %d \n", premier_arrive);
}
return 0;}
4 TP N°3