C processes in Linux
From Teknologisk videncenter
Example of creating several processes
See same example in bash
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4 #include <wait.h>
5 // No errorchecking in this example code
6 void childprocess(char *name, int count_to) {
7 int counter = 0;
8
9 printf("My name is %s and my PID is %d\n", name, getpid());
10
11 while (counter < count_to) {
12 sleep(1);
13 counter = counter +1;
14 printf("%s counted to %i\n", name, counter);
15 }
16 printf("%s signing off", name);
17 }
18
19
20 int main(void) {
21 int wstatus; // Used by c wait function
22
23 printf("I am the main function and my PID is %i\n", getpid());
24
25 if (fork() == 0) { // fork returns 0 for child
26 childprocess("Hans", 5);
27 return(0); // Child process finished
28 }
29
30 if (fork() == 0) {
31 childprocess("Ulla", 3);
32 return(0);
33 }
34
35 while(wait(&wstatus) > 0);
36 return(0);
37 }