Difference between revisions of "C processes in Linux"

From Teknologisk videncenter
Jump to: navigation, search
m (Advanced)
m (Replaced content with " =Advanced= ==prctl== prctl - operations on a process <source lang=c> // Changing the name of running proces #include <sys/prctl.h> ... prctl(PR_SET_NAME, "newname")...")
Line 1: Line 1:
{{TOCright}}
 
'''fork()''' is one of several functions to "spawn" a process
 
=Use of fork=
 
[[Fork system call|fork()]] creates a new process by duplicating the calling process.  The new process is referred to as the child process.  The calling process is referred to as the parent process.
 
*PID - Process ID - the ID of a running process
 
*PPID - Parent Process ID - default the ID of the process that created this process or 1 if the parent died.
 
<source lang=c line>
 
#include <stdio.h>
 
#include <sys/types.h>
 
#include <unistd.h>
 
  
  
int main(void) {
 
        printf("I am parent - my PPID is %d and my PID is %d\n", getppid(), getpid() );
 
 
        if (fork() == 0) {
 
                printf("I am child  - my PPID is %d and my PID is %d\n", getppid(), getpid() );
 
                printf("Child  dying\n");
 
                return(0);
 
        }
 
        printf("parent dying\n");
 
        return(0);
 
}
 
</source>
 
 
==Example of creating a daemon in Linux==
 
{{:Daemon linux}}
 
 
=Example of creating several processes=
 
See same example in [[Bash processes#example|bash]]
 
<source lang=c line>
 
#include <stdio.h>
 
#include <sys/types.h>
 
#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);
 
}
 
 
</source>
 
 
=Advanced=
 
=Advanced=
  
Line 81: Line 12:
 
...
 
...
 
</source>
 
</source>
 +
[[Category:Linux]][[Category:C]]

Revision as of 07:42, 17 December 2022


Advanced

prctl

prctl - operations on a process

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