Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- enum { FD_PIPE = 2 };
- void stop(int *z, int n){
- int i;
- for(i = 0; i <= n; i++){
- kill(z[i], SIGKILL);
- }
- while(wait(NULL) > 0) {};
- free(z);
- exit(1);
- }
- int
- main(int argc, char **argv)
- {
- int fd[FD_PIPE], i;
- int *z = malloc(sizeof(int) * argc);
- if(!z){
- exit(1);
- }
- for (i = 1; i < argc - 1; i++) {
- if(pipe(fd) < 0){
- i--;
- stop(z, i - 1);
- }
- if (!(z[i-1] = fork())) {
- close(fd[0]);
- dup2(fd[1], 1);
- close(fd[1]);
- execlp(argv[i], argv[i], NULL);
- _exit(1);
- } else if(z[i-1] > 0){
- if(close(fd[1])){
- stop(z, i - 1);
- }
- if(dup2(fd[0], 0) < 0){
- close(fd[0]);
- stop(z, i - 1);
- }
- if(close(fd[0])){
- stop(z, i - 1);
- }
- } else{
- if(close(fd[0])){
- stop(z, i - 1);
- }
- if(close(fd[1])){
- stop(z, i - 1);
- }
- i--;
- stop(z, i - 1);
- }
- }
- if(argc > 1){
- argc--;
- if (!(z[argc - 1] = fork())) {
- execlp(argv[argc], argv[argc], NULL);
- _exit(1);
- } else if(z[argc - 1] > 0){
- if(close(0)){
- stop(z, argc - 1);
- }
- while(wait(NULL) > 0) {};
- free(z);
- return 0;
- } else{
- stop(z, argc - 1);
- }
- } else{
- while(wait(NULL) > 0) {};
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement