Browse Source

Fin TP9&10

master
Elias Leinenweber 4 months ago
parent
commit
2ffacaf1f3
  1. 82
      TP9and10/fork-exercice.c

82
TP9and10/fork-exercice.c

@ -1,49 +1,73 @@
#include <sys/wait.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void child_function(int child_number);
void father_function();
static void usage(void);
int main (int argc, char *argv[]) {
int nb_of_processes, i_child, pid_child;
void child_function(int);
void father_function();
/* Check that one parameter was provided */
if (argc != 2) {
printf(" Wrong usage, expected : %s number_of_processes ! \n", argv[0]);
exit(2);
}
static void
usage(void)
{
extern char *__progname;
nb_of_processes = atoi (argv [1]); /* conversion ascii -> integer */
fprintf(stderr, "usage: %s number_of_processes\n", __progname);
exit(1);
}
/* ----------------------------------------
* creation of children processes
* ----------------------------------------
*/
for ( i_child =1; i_child <= nb_of_processes ; i_child++ ) {
pid_child = fork();
switch (pid_child) {
case 0 :
child_function(i_child); /* You have to write this function ... */
break;
case -1 :
perror("Fork just failed !!!");
exit(33); /* exit in case an error occured */
}
}
int
main(int argc, char *argv[])
{
int nb_of_processes, i_child, pid_child;
father_function(); /* You have to write this function ... */
/* check that one parameter was provided */
if (argc != 2)
usage();
return 0;
nb_of_processes = atoi(argv[1]);
/* creation of children processes */
for (i_child = 1; i_child <= nb_of_processes; ++i_child) {
pid_child = fork();
switch (pid_child) {
case 0:
child_function(i_child);
break;
case -1:
err(EXIT_FAILURE, "fork");
}
}
father_function();
exit(EXIT_SUCCESS);
}
void child_function(int child_number)
void
child_function(int child_number)
{
int div_zero;
printf("executing process %d, parent is process %d\n", getpid(), getppid());
printf("going to wait...\n");
sleep(2 * child_number);
div_zero = 1 / (1 - child_number);
exit(child_number);
}
void father_function()
void
father_function()
{
int ret, state;
do {
ret = wait(&state);
if (ret != -1)
printf("Child finished its execution, pid: %d\nIts state was: %04x\n", ret, state);
} while (ret != -1);
}

Loading…
Cancel
Save