IPC using Pipes

This commit is contained in:
2024-05-01 15:10:55 +05:30
parent 52bad283ed
commit 8741cb43f4
2 changed files with 41 additions and 0 deletions

View File

@@ -18,6 +18,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
# Add source to this project's executable.
add_executable (Pipes_demo "Pipes_demo.c" )
add_executable (2ProcessPipes "2ProcessPipes.c")
add_executable (Challenge "Challenge.c")

40
Pipes/Challenge.c Normal file
View File

@@ -0,0 +1,40 @@
/*
To implement "ls | wc -l" in C.
This only work in linux system.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int pfds[2];
pipe(pfds);
/*
dup(int fd) : it duplicates the specified fd to the free fd value with lowest
numeric value.
*/
if (!fork()) {
close(1); /* closing the stdout whose fd value is 1 for a process. */
dup(pfds[1]); /* setting the stdout of process to writing end of the pipe. */
close(pfds[0]); /* Reading end of the pipe is not needed by the child process. */
execlp("ls", "ls", NULL);
}
else {
close(0); /* closing the stdin whose fd value 0 for a process. */
dup(pfds[0]); /* setting the stdin of process to reading end of the pipe. */
close(pfds[1]); /* Writing end of the pipe is not needed by the parent process. */
execlp("wc", "wc", "-l", NULL);
}
return 0;
}