Advertisement
Tavi33

SO #6

Nov 8th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6.  
  7. int main(int argc, char *args[]) {
  8. if(argc < 3) {
  9. fprintf(stderr, "Usage: %s <number> <file1> <file2> ...\n", args[0]);
  10. exit(1);
  11. }
  12.  
  13. int pid;
  14. int i = 0;
  15.  
  16. if((pid=fork()) < 0)
  17. {
  18. perror("ERROR");
  19. exit(1);
  20. }
  21. if(pid==0)
  22. {
  23. for(i = 0; i <= atoi(args[1]); i++) {
  24. printf("%d: %d\n", getpid(), i);
  25. }
  26. exit(0);
  27. }
  28. for(i = 2; i <= argc-1; i++) {
  29. if((pid=fork()) < 0)
  30. {
  31. perror("ERROR");
  32. exit(1);
  33. }
  34. if(pid==0)
  35. {
  36. char *argv[] = { "wc", args[i], "-l", 0 };
  37. execvp(argv[0], argv);
  38. } else {
  39. int status;
  40. wait(&status);
  41. if (WIFEXITED(status)) {
  42. printf("PID: %d exited, status=%d\n", pid, WEXITSTATUS(status));
  43. } else if (WIFSIGNALED(status)) {
  44. printf("PID: %d killed by signal %d\n", pid, WTERMSIG(status));
  45. } else if (WIFSTOPPED(status)) {
  46. printf("PID: %d stopped by signal %d\n", pid, WSTOPSIG(status));
  47. } else if (WIFCONTINUED(status)) {
  48. printf("PID: %d continued\n", pid);
  49. }
  50. }
  51. }
  52.  
  53. return 1;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement