Difference between revisions of "C processes in Linux"

From Teknologisk videncenter
Jump to: navigation, search
m (Example of creating several processes)
m
 
(13 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.
See same example in [[Bash processes#example|bash]]
+
*Most used:
<source lang=c line>
+
**[[fork system call]] family  ("clone" a runnning process to two running instances of the same code)
#include <stdio.h>
+
**[[exec system call]] family (Execute a file)
#include <sys/types.h>
+
*But also:
#include <unistd.h>
+
**[[clone system call]] (Like [[fork system call|fork]] - but more advanced)
#include <wait.h>
+
**[[system and popen system call]]  (Can give security issues)
 
+
=Advanced=
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 08: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