Linux system programming: Process primitives, linux programming process primitives

Source: Internet
Author: User

Linux system programming: Process primitives, linux programming process primitives

Process primitives

1. Process is a running activity of a program on a dataset in a computer. It is the basic unit for the system to allocate and schedule resources and the basis of the operating system structure.
2. process environment
The global variable environ defined in libc points to the environment variable table. environ is not included in any header file. Therefore, use extern to declare it during use. Use the following code to view information about all environment variables of the current process.

#include <stdio.h> int main(void){    extern char **environ;    int i;    for(i = 0; environ[i] != NULL;  i++)    printf("%s\n", environ[i]);    return 0;}

The running result displays environment variable information in the form of key-value pairs. Several common environment variables:
PATH: The Search PATH of the executable file.
SHELL: The current shell.
HOME: The Path to the HOME Directory of the current user.
3. Process status
Four major process statuses: running, ready, suspended, and terminated.
4. Process primitives
Use the fork function in liunx to create a new process.

#include <unistd.h>pid_t fork(void);

Function features: Call once and return twice.
In the parent process, the pid of the created child process is returned; 0 is returned in the child process;-1 is returned if an error occurs.
An instance that creates a sub-process:

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> # include <sys/types. h> void sys_err (char * s) {perror (s); exit (1) ;}int main (void) {pid_t pid; pid = fork (); if (pid <0) sys_err ("fork"); else if (pid> 0) {/* parent process */printf ("I am parent, my pid is % d, my parent pid is % d \ n ", getpid (), getppid (); sleep (1); // sleep for 1 second, prevent the parent process from exiting too early} else {/* child process */printf ("I am child, my pid is % d, my parent pid is % d \ n ", getpid (), getppid ();} return 0;} // I am child, my pid is 15057, my parent pid is 15056 // I am parent, my pid is 15056, my parent pid is 5292
# Include <unistd. h> # include <sys/types. h> // defines pid_t, uid_t, and gid_tpid_t getpid (void); // gets the pidpidpid_t getppid (void) of the current process ); // obtain the piduid_t getuid (void) of the parent process of the current process; // return the actual user iduid_t geteuid (void); // return the valid user idgid_t getgid (void ); // return the actual user group idgid_t getegid (void); // return the valid user group id

All IDS are positive.
Relationship between parent and child processes:
1. The child process copies the PCB (except pid), code segment, and data zone of the parent process.
2. after a child process is created with fork, it executes the same program as the parent process (but may execute different code branches). A child process usually calls one exec function to execute another program. When a process calls an exec function, the user space code and data of the process are completely replaced by the new program, and the execution starts from the startup routine of the new program. Calling exec does not create a new process, so the id of the process does not change before and after exec is called.
5. exec family

#include <unistd.h>int execl(const char *path, const char *arg, ...);int execlp(const char *file, const char *arg, ...);int execle(const char *path, const char *arg, ..., char *const envp[]);int execv(const char *path, char *const argv[]);int execvp(const char *file, char *const argv[]);int execve(const char *path, char *const argv[], char *const envp[]);

You only need to understand the use of execl. The other steps are the opposite: path indicates the path of the new executable program, followed by arg, which is the provided parameter.
Use the execl function to change program execution:

// Show. c # include <stdio. h> int main (int argc, char ** argv) {int I = 0; while (I <argc) printf ("% s \ n ", argv [I ++]); return 0;} // app. c # include <stdio. h> # include <unistd. h> # include <stdlib. h> int main (int argc, char ** argv) {if (argc <2) {fprintf (stderr, "usage: app newapp... "); exit (1);} printf (" zhangxiang \ n "); // $ argv [1] zx zhangxiangDavid@126.com execl (argv [1]," zx ", "zhangxiangDavid@126.com", NULL); // NULL indicates the end of the parameter list printf ("David \ n"); return 0;} $ gcc show. c-o show $ gcc app. c-o app $ app showzhangxiangzxzhangxiangDavid@126.com

After printf ("zhangxiang \ n") is executed, the code segment of the program is replaced, so the printf ("David \ n") of the original program is not executed.

L command line parameter list
Use the path variable when searching for p files
V use the command line parameter Array
E. Use the environment variable array instead of the original environment variable of the process. Set the environment variable for the newly loaded program.
If these functions are successfully called, a new program is loaded and executed starting from the startup code. If an error is returned,-1 is returned. Therefore, the exec function only returns an error but fails to return a success.
6. wait (), waitpid ()
Zombie process: the child process exits. If the parent process does not recycle the child process resources (PCB), the child process becomes a zombie process.
Orphan process: the parent process ends before the child process, the child process becomes an orphan process, the child process of the parent process becomes the init process of process 1, called the init process to adopt orphan process.
After the child process ends, the PCB remains in the memory. The parent process can obtain the exit status of the child process through the pcb of the child process: the exit code when the child process Exits normally, and the signal that terminates the child process when the child process exits abnormally.

#include <sys/types.h>#include <sys/wait.h>pid_t wait(int *status);

Function Description:
The output parameter status is used to record the exit status.
When no sub-process exits, wait calls will block the current process.
Succeeded. The pid of the sub-process is returned;
Failed.-1 is returned;

#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/wait.h>int main(void){    pid_t pid, wpid;    pid = fork();    if(0 == pid)    {        printf("in child\n");        sleep(2);        printf("child exit\n");    }    else if(pid > 0)    {        while(1)        {            wpid = wait(NULL);            printf("in parent %d\n", wpid);            sleep(1);        }    }    else    {        perror("fork");        exit(1);    }    return 0;}//in child//child exit//in parent 27909//in parent -1//in parent -1//^c

Wait () will block the parent process. To avoid blocking, you need to use waitpid ()

#include <sys/types.h>#include <sys/wait.h>pid_t waitpid(pid_t pid, int *status, int options);

Function Description:
Pid indicates the pcb of the child process to be recycled;
Change the function running status by specifying the options value. (In particular, specifying WNOHANG will not block ).
Specify the WNOHANG, after non-blocking. If no process exits, 0 is returned.

#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/wait.h>int main(void){    pid_t pid, wpid;    pid = fork();    if(0 == pid)    {        printf("in child\n");        sleep(2);        printf("child exit\n");    }    else if(pid > 0)    {        while(1)        {            wpid = waitpid(0, NULL, WNOHANG);            printf("in parent %d\n", wpid);            sleep(1);        }    }    else    {        perror("fork");        exit(1);    }    return 0;}//in parent 0//in child//in parent 0//child exit//in parent 28700//in parent -1//in parent -1//^c

CCPP Blog directory

Copyright Disclaimer: This article is an original article by the blogger. For more information, see the source.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.