Difference between revisions of "C processes in Linux"

From Teknologisk videncenter
Jump to: navigation, search
m
m
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{TOCright}}
+
There are several ways of creating a new process.
===Example of creating a daemon in Linux===
+
*Most used:
{{:Daemon linux}}
+
**[[fork system call]] family  ("clone" a runnning process to two running instances of the same code)
===Example of creating several processes===
+
**[[exec system call]] family (Execute a file)
See same example in [[Bash processes#example|bash]]
+
*But also:
<source lang=c line>
+
**[[clone system call]] (Like [[fork system call|fork]] - but more advanced)
#include <stdio.h>
+
**[[system and popen system call]]  (Can give security issues)
#include <sys/types.h>
+
=Advanced=
#include <unistd.h>
 
#include <wait.h>
 
 
 
void childprocess(char *name, int count_to) {
 
        int counter = 0;
 
 
 
        printf("My name is %s and my PID is %d\n", name, getpid());
 
 
 
        while (counter < count_to) {
 
                sleep(1);
 
                counter = counter +1;
 
                printf("%s counted to %i\n", name, counter);
 
        }
 
        printf("%s signing off\n", 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);
 
        printf("Main signing off\n");
 
        return(0);
 
}
 
  
 +
==prctl==
 +
prctl - operations on a process
 +
<source lang=c>
 +
// Changing the name of running proces
 +
#include <sys/prctl.h>
 +
...
 +
    prctl(PR_SET_NAME, "newname");
 +
...
 
</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