Difference between revisions of "C processes in Linux"

From Teknologisk videncenter
Jump to: navigation, search
(Created page with "===Example of creating several processes=== <source lang=c line> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <wait.h> void childprocess(char *name,...")
 
m
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
===Example of creating several processes===
+
There are several ways of creating a new process.
<source lang=c line>
+
*Most used:
#include <stdio.h>
+
**[[fork system call]] family  ("clone" a runnning process to two running instances of the same code)
#include <sys/types.h>
+
**[[exec system call]] family (Execute a file)
#include <unistd.h>
+
*But also:
#include <wait.h>
+
**[[clone system call]] (Like [[fork system call|fork]] - but more advanced)
 +
**[[system and popen system call]]  (Can give security issues)
 +
=Advanced=
  
void childprocess(char *name, int count_to) {
+
==prctl==
        int counter = 0;
+
prctl - operations on a process
 
+
<source lang=c>
        printf("My name is %s and my PID is %d\n", name, getpid());
+
// Changing the name of running proces
 
+
#include <sys/prctl.h>
        while (counter < count_to) {
+
...
                sleep(1);
+
    prctl(PR_SET_NAME, "newname");
                counter = counter +1;
+
...
                printf("%s counted to %i\n", name, counter);
 
        }
 
        printf("%s signing off", name);
 
}
 
 
 
 
 
int main(void) {
 
        int wstatus; // Used by c wait function
 
 
 
        printf("I am the main function and my PID is %i\n", getpid());
 
 
 
        if (fork() == 0) { // fork returns 0 for child
 
                childprocess("Hans", 5);
 
                return(0);      // Child process finished
 
        }
 
 
 
        if (fork() == 0) {
 
                childprocess("Ulla", 3);
 
                return(0);
 
        }
 
 
 
        while(wait(&wstatus) > 0);
 
        return(0);
 
}
 
 
</source>
 
</source>
 +
=Links=
 +
*[http://boron.physics.metu.edu.tr/ozdogan/SystemsProgramming/week4/node8.html Creating processes]
 +
[[Category:Linux]][[Category:C]]

Latest revision as of 07:59, 17 December 2022

There are several ways of creating a new process.

Advanced

prctl

prctl - operations on a process

// Changing the name of running proces
#include <sys/prctl.h>
...
    prctl(PR_SET_NAME, "newname");
...

Links