Created
September 9, 2019 18:27
-
-
Save varun1729/960108137c82fef0ea638ddf2f02b64b to your computer and use it in GitHub Desktop.
du | sort -n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pid_t sortPID = fork(); | |
if(sortPID < 0) | |
perror("cannot fork a process for sort"); | |
else if(sortPID == 0){ | |
//Forked process --> child: sort. | |
int fd[2]; | |
//sort child opens the pipes. | |
if (pipe(fd) < 0) | |
perror("cannot create pipe"); | |
close(fd[1]); //We're not going to write to the pipe, so close it. | |
//Child forks to create grandchild. | |
pid_t duPID = fork(); | |
if(duPID < 0) | |
perror("cannot fork for du"); | |
else if (duPID == 0) { | |
//Forked process --> grand child: du | |
close(fd[0]); //We won't read from the pipe, so close it. | |
dup2(fd[1], 1); //Since du will use the write-end of the pipe created (by the forked process of sort), we need to duplicate it to file descriptor 1. | |
close(fd[1]);//We will no longer access the write end of the pipe through fd[1]; we can close it. | |
execlp("du"); //This command should not return if there is no error | |
perror("du failed to execute properly"); //Print error in execution of du; e.g. du could not be found in $PATH | |
} else { | |
//Forked process --> child: sort | |
dup2(fd[0], 0);//The read end of the pipe will be used as standard input by sort | |
execlp("sort", "-n");//Again this should not return unless there is an error | |
perror();//Print error in executing of sort | |
} | |
} else { | |
int status; | |
if (waitpid(c,&status, NULL) < 0)//waitpid returns a value less than 0; if it encounters an error. Here, we wait for sort. | |
perror("cannot wait for sort"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment