diff --git a/Pipes/2ProcessPipes.c b/Pipes/2ProcessPipes.c new file mode 100644 index 0000000..cbbfcb5 --- /dev/null +++ b/Pipes/2ProcessPipes.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include +#include + +int main(int argc, char* argv[]) { + + int pfds[2]; + char buf[30]; + + pipe(pfds); + + + /* + fork() : + -> Generate the clone of the calling process. + -> Calling process is parent process and new + process is child process. + -> Return value : + 1. value 0 : means the current process is child process + which is newly forked and forking is successful. + 2. value -1 : means the forking the process has failed. + The value is retured to parent process. + 3. value : means the current process is + parent process and it is the process id of + the newly forked child process on the system. + */ + if (!fork()) { + + printf(" CHILD : writing to the pipe\n"); + write(pfds[1], "test", 5); + printf(" CHILD: exiting\n"); + exit(0); + } + else { + printf("PARENT: reading from pipe\n"); + read(pfds[0], buf, 5); + printf("PARENT: read \"%s\"\n", buf); + wait(NULL); + } + + /* + The parent process should wait for forked child + process to finish the execution and notify the parent. + Otherwise, the parent would also terminating without + knowing the process execution info about the child + process and the child process would keep running turning + itself to a zombie process. + Here, we use wait() sys call for parent to wait for + child process. + */ + return 0; +} \ No newline at end of file diff --git a/Pipes/CMakeLists.txt b/Pipes/CMakeLists.txt new file mode 100644 index 0000000..7f0dfc9 --- /dev/null +++ b/Pipes/CMakeLists.txt @@ -0,0 +1,24 @@ +# CMakeList.txt : CMake project for Pipes, include source and define +# project specific logic here. +# +cmake_minimum_required (VERSION 3.8) + +# Enable Hot Reload for MSVC compilers if supported. +if (POLICY CMP0141) + cmake_policy(SET CMP0141 NEW) + set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$,$>,$<$:EditAndContinue>,$<$:ProgramDatabase>>") +endif() + +project(Pipes VERSION 1.0.0 LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Add source to this project's executable. +add_executable (Pipes_demo "Pipes_demo.c" ) +add_executable (2ProcessPipes "2ProcessPipes.c") + + + +# TODO: Add tests and install targets if needed. diff --git a/Pipes/Pipes_demo.c b/Pipes/Pipes_demo.c new file mode 100644 index 0000000..e19510d --- /dev/null +++ b/Pipes/Pipes_demo.c @@ -0,0 +1,23 @@ +#include +#include +#include +#include + +int main(int argc, char* argv[]) { + + int pfds[2]; + char buf[30]; + + if (pipe(pfds) == -1) { + perror("pipes"); + exit(1); + } + + printf("writing to file descriptor #%d\n", pfds[1]); + write(pfds[1], "test", 5); + printf("reading from file descriptor #%d\n", pfds[0]); + read(pfds[0], buf, 5); + printf("read \"%s\"\n", buf); + + return 0; +} \ No newline at end of file