Difference between revisions of "C processes in Linux"

From Teknologisk videncenter
Jump to: navigation, search
m (Example of creating several processes)
m (Example of creating several processes)
Line 6: Line 6:
 
#include <unistd.h>
 
#include <unistd.h>
 
#include <wait.h>
 
#include <wait.h>
// No errorchecking in this example code
+
 
 
void childprocess(char *name, int count_to) {
 
void childprocess(char *name, int count_to) {
 
         int counter = 0;
 
         int counter = 0;
Line 17: Line 17:
 
                 printf("%s counted to %i\n", name, counter);
 
                 printf("%s counted to %i\n", name, counter);
 
         }
 
         }
         printf("%s signing off", name);
+
         printf("%s signing off\n", name);
 
}
 
}
  
Line 37: Line 37:
  
 
         while(wait(&wstatus) > 0);
 
         while(wait(&wstatus) > 0);
 +
        printf("Main signing off\n");
 
         return(0);
 
         return(0);
 
}
 
}
 +
 
</source>
 
</source>

Revision as of 09:42, 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\n", 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         printf("Main signing off\n");
37         return(0);
38 }