From 8741cb43f40372823a836a35a7b078a0e3b428ba Mon Sep 17 00:00:00 2001 From: Hizenberg Date: Wed, 1 May 2024 15:10:55 +0530 Subject: [PATCH] IPC using Pipes --- Pipes/CMakeLists.txt | 1 + Pipes/Challenge.c | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 Pipes/Challenge.c diff --git a/Pipes/CMakeLists.txt b/Pipes/CMakeLists.txt index 7f0dfc9..b4c8224 100644 --- a/Pipes/CMakeLists.txt +++ b/Pipes/CMakeLists.txt @@ -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") diff --git a/Pipes/Challenge.c b/Pipes/Challenge.c new file mode 100644 index 0000000..c7b8398 --- /dev/null +++ b/Pipes/Challenge.c @@ -0,0 +1,40 @@ +/* + To implement "ls | wc -l" in C. + This only work in linux system. +*/ + + +#include +#include +#include + +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; +} \ No newline at end of file