commit 9ba8b104d0069789ac029ab2933923eee031ddc0 Author: leonnicolas Date: Wed Jun 3 15:15:05 2020 +0200 initial commit diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..85a41b9 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +main: main.c + gcc -pedantic -Wall -o main main.c diff --git a/README.md b/README.md new file mode 100644 index 0000000..f3e48c6 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# Simple Fork Example +A simple example using fork() in C. + +## Compile +```bash +make +``` +## Run +```bash +./main +``` diff --git a/main.c b/main.c new file mode 100644 index 0000000..feec2a3 --- /dev/null +++ b/main.c @@ -0,0 +1,50 @@ +/* + * ===================================================================================== + * + * Filename: main.c + * + * Description: basic example of multi processing with fork() + * + * Version: 1.0 + * Created: 06/03/2020 01:54:39 PM + * Revision: none + * Compiler: gcc + * + * Author: Leon Löchner + * Organization: + * + * ===================================================================================== + */ +#include +#include +#include +#include +#include +#include + +#define NUM_PROCESS 3 + +void errExit(char* msg){ + perror(msg); + exit(EXIT_FAILURE); +} + +int main(){ + pid_t *pids = malloc(NUM_PROCESS * sizeof(pid_t)); + for (int i = 0 ; i < NUM_PROCESS ; i++){ + pids[i] = fork(); + if (pids[i] < 0){ + errExit("fork failed"); + } + if (pids[i] == 0 ){ + printf("child is running...\n"); + sleep(10); + exit(0); + } + } + printf("parent waiting for children...\n"); + int status, pid; + while ((pid = wait(&status)) > 0){ + printf("child process %d terminated with status %d\n", pid, WEXITSTATUS(status)); + } +}