#include #include #include #include #include #include int main (int argc, char** argv) { int status, n_read, fd; char buf[11]; pid_t child_pid; // Open a file fd = open ("un.fisier", O_RDONLY); if (fd < 0) { perror ("open un.fisier"); exit (EXIT_FAILURE); } // The fork syscall. From here on, two processes will run the code. child_pid = fork(); switch (child_pid) { // fork error case -1: perror("fork"); return EXIT_FAILURE; // child code case 0: { printf("Child here. My pid is %d. Parent's pid is %d\n", getpid(), getppid()); sleep(3); // sleep for a while // read and print some characters from file n_read = read(fd, buf, 3); if (n_read < 0) { perror ("Child:reading file"); exit (EXIT_FAILURE); } buf[n_read] = '\0'; printf("Child here. I've read '%s' from the file. I'm going to finish now\n", buf); break; } // parent code default: { printf("Parent here. My pid is %d. Child's pid is %d\n", getpid(), child_pid); // wait for child to end execution pid_t waited_pid = waitpid(child_pid, &status, 0); if (waited_pid < 0) { perror("waitpid"); return EXIT_FAILURE; } printf("Parent here. Succesfully waited for child %d\n", waited_pid); // read and print some characters from file n_read = read(fd, buf, 3); if (n_read < 0) { perror ("Parent:reading file"); exit (EXIT_FAILURE); } buf[n_read] = '\0'; printf("Parent here. I've read '%s' from the file. I'm going to finish now\n", buf); } } close(fd); return 0; }