Difference between revisions of "C processes in Linux"
From Teknologisk videncenter
m (→Example of creating several processes) |
m (→Example of creating several processes) |
||
Line 1: | Line 1: | ||
===Example of creating several processes=== | ===Example of creating several processes=== | ||
− | See same example in [[Bash processes|bash]] | + | See same example in [[Bash processes#example|bash]] |
<source lang=c line> | <source lang=c line> | ||
#include <stdio.h> | #include <stdio.h> |
Revision as of 09:38, 16 December 2022
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
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 }