2) getting started with Linux programming-process Introduction

Source: Internet
Author: User

2) getting started with Linux programming-process Introduction
Process Creation in Linux
Preface:
This article introduces various process-related concepts in Linux. We will learn:
Process Concept
Process Identity
Process Creation
Creation of daemon
----------------------------------------------------------------------------
1. Process Concept
The Linux operating system is designed for multiple users. At the same time, many users can send various types of messages to the operating system.
So how does the operating system implement a multi-user environment? In modern operating systems, there are programs and processes.
So what is a program and a process? In general, a program is a file containing executable code.
Is a static file, and the process is an instance of the program that starts execution but has not ended. It is an executable file.
A program may have many processes, and each process can have many sub-processes.
When the program is called to the memory, the system will allocate some resources to the Program (
Storage, devices, etc.) and then perform a series of complex operations to turn the program into a process for the system to call.
A process has no program. to distinguish different processes, the system assigns an ID to each process (just like our
ID card) for identification. In order to make full use of resources, the system also distinguishes processes from different States.
Five statuses are created, run, blocked, ready, and completed. Creating indicates that the process is being created, and running indicates that the process is running and blocked.
The process is waiting for an event to occur. The ready means that the system is waiting for the CPU to execute the command, and the finished means
The process has ended and the system is recycling resources. For more information about the five States of the process, see Operating System
It provides a detailed explanation.
2. Process flag
As we know above that all processes have an ID, how can we get the ID of the process? The getpid can be called by the system.
Get the process ID, and getppid can get the ID of the parent process (the process that creates the process that calls this function.
# Include <unistd>
Pid_t getpid (void );
Pid_t getppid (void );
The process serves the program, and the program serves the user. The system finds the User Name of the process
The user establishes a contact. This user is called the process owner. Each user also has a user ID.
You can call getuid to obtain the ID of the process owner. Because the process requires some resources
To obtain a certain resource process, there is a valid user ID. This ID is related to the system resource usage.
Process permissions. By calling geteuid, we can obtain the valid user ID and user ID of the process.
The corresponding process also has a group ID and a valid group ID. The system calls getgid and getegid to obtain the group ID and valid group ID respectively.
Group ID
# Include <unistd>
# Include <sys/types. h>

Uid_t getuid (void );
Uid_t geteuid (void );
Gid_t getgid (void );
Git_t getegid (void );
Sometimes we are also interested in other user information (login name, etc.). At this time, we can call getpwui
D.
Struct passwd {
Char * pw_name;/* logon name */
Char * pw_passwd;/* logon password */
Uid_t pw_uid;/* User ID */
Gid_t pw_gid;/* User Group ID */
Char * pw_gecos;/* User's real name */
Char * pw_dir;/* user directory */
Char * pw_shell;/* User's shell */
};
# Include <PWD. h>
# Include <sys/types. h>

Struct passwd * getpwuid (uid_t UID );
Next we will learn an example to practice the functions we have learned above:
# Include <unistd. h>
# Include <PWD. h>
# Include <sys/types. h>
# Include <stdio. h>
Int main (INT argc, char ** argv)
{
Pid_t my_pid, parent_pid;
Uid_t my_uid, my_euid;
Gid_t my_gid, my_egid;
Struct passwd * my_info;
My_pid = getpid ();
Parent_pid = getppid ();
My_uid = getuid ();
My_euid = geteuid ();
My_gid = getgid ();
My_egid = getegid ();
My_info = getpwuid (my_uid );
Printf ("process ID: % LD/N", my_pid );
Printf ("parent ID: % LD/N", parent_pid );
Printf ("User ID: % LD/N", my_uid );
Printf ("valid tive user ID: % LD/N", my_euid );
Printf ("group ID: % LD/N", my_gid );
Printf ("valid tive group ID: % LD/N", my_egid ):
If (my_info)
{
Printf ("My login name: % s/n", my_info-> pw_name );
Printf ("My password: % s/n", my_info-> pw_passwd );
Printf ("My User ID: % LD/N", my_info-> pw_uid );
Printf ("My group ID: % LD/N", my_info-> pw_gid );
Printf ("My real name: % s/n", my_info-> pw_gecos );
Printf ("My home dir: % s/n", my_info-> pw_dir );
Printf ("My work shell: % s/n", my_info-> pw_shell );
}
}
3. Process Creation
It is easy to create a system call for a process. You only need to call the fork function.
# Include <unistd. h>

Pid_t fork ();
After a process calls fork, the system creates a sub-process. This sub-process is different from the parent process only
With the process ID and parent process ID, the others are the same. Just like the process clone (clone) itself. Of course, create
Two identical processes are meaningless. To distinguish Parent and Child processes, we must track fork responses.
Value. When the fork fails to be used (the memory is insufficient or the maximum number of processes of the user has reached), fork returns-1; otherwise, F
The returned value of Ork plays an important role. For the parent process fork to return the ID of the child process, and for the Fork sub-process to return 0. I
The Parent and Child processes are differentiated based on the returned values. Why should a parent process create a child process? We have
Linux is a multi-user operating system. At the same time, many users compete for system resources.
The process creates a sub-process to compete for resources to complete the task earlier. Once the sub-process is created, the Parent and Child Processes
Fork continues to execute, competing for system resources. Sometimes we want the sub-process to continue to execute, and the parent process is blocked directly.
At this time, we can call the wait or waitpid system.
# Include <sys/types. h>
# Include <sys/Wait. H>

Pid_t wait (int * stat_loc );
Pid_t waitpid (pid_t PID, int * stat_loc, int options );
Wait system calls will block the parent process until a child process ends or the parent process receives a signal. If
No parent process, no child process, or its child process has ended, wait returns immediately.
(End) wait will return the ID of the sub-process; otherwise,-1 will be returned, and the global variable errno. stat_loc will be set to the sub-process
Exit status. The sub-process calls exit, _ exit, or return to set this value.
To test the returned value.
Wifexited: determines whether the sub-process exit value is non-0.
Wexitstatus: determines the exit value of the sub-process (not 0 when the sub-process exits ).
Wifsignaled: The child process exits because of the signal obtained.
Wtermsig: the signal number not obtained by the sub-process (it makes sense when wifsignaled is true ).
Waitpid waits for the specified sub-process until the sub-process returns. If the PID is positive, it waits for the specified process (PID). If
If the value is 0, the process waits for any group ID to be the same as the caller's group ID. If it is-1, it is equivalent to wait call. If it is less than-1, etc.
The process where any group ID is equal to the absolute value of PID. stat_loc has the same meaning as wait. options can be determined.
The status of the parent process. Two values can be taken: wnohang: the parent process returns immediately when no child process exists. wuntache
D: The waitpid is returned when the child process ends, but the exit status of the child process cannot be obtained.
After the parent process creates a child process, the child process generally needs to execute different programs. To call the system program, we can use
You can call the C-class .exe by using the 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 ,...);
Int execv (const char * path, char * const argv []);
Int execvp (const char * file, char * const argv []):
Exec invocation can execute a given program. For details about invocation of exec, refer to the System Manual (man Exec
L). Next we will learn an example. Note that-LM should be added during compilation to connect to the mathematical function library.
# Include <unistd. h>
# Include <sys/types. h>
# Include <sys/Wait. H>
# Include <stdio. h>
# Include <errno. h>
# Include <math. h>
Void main (void)
{
Pid_t child;
Int status;
Printf ("This will demostrate how to get child status/N ");
If (child = fork () =-1)
{
Printf ("fork error: % s/n", strerror (errno ));
Exit (1 );
}
Else if (child = 0)
{
Int I;
Printf ("I am the child: % LD/N", getpid ());
For (I = 0; I <1000000; I ++) sin (I );
I = 5;
Printf ("I exit with % d/N", I );
Exit (I );
}
While (child = wait (& Status) =-1) & (errno = eintr ));
If (child =-1)
Printf ("Wait error: % s/n", strerror (errno ));
Else if (! Status)
Printf ("child % LD terminated normally return status is zero/N ",
Child );
Else if (wifexited (Status ))
Printf ("child % LD terminated normally return status is % d/N ",
Child, wexitstatus (Status ));
Else if (wifsignaled (Status ))
Printf ("child % LD terminated due to signal % d znot caught/N ",
Child, wtermsig (Status ));
}
The strerror function returns a string with the specified error code.
4. Creation of daemon
If you have written a program in the DOS era, you may know that in DOS, to write a program with resident memory
How much code should we write? On the contrary, it would be easy to write a "resident memory" program in Linux.
We only need a few lines of code. In fact, because Linux is a multi-task operating system, we simply do not write code.
You can also put a program in the background for execution. We only need to add the & Symbol shell after the command to put our
The program runs in the background. Here we "develop" A background email check program. Each program
Go back to check our mailbox at a specified time. If we find that we have emails, we will keep sending alarms (through the small box on the chassis ).
). The enhanced version of this function is later.
Background Process Creation idea: first, the parent process creates a sub-process, and then the sub-process kills the parent process (is it very useless?
Love ?). All tasks of signal processing are processed by sub-processes.
# Include <unistd. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <stdio. h>
# Include <errno. h>
# Include <fcntl. h>
# Include <signal. h>
/* The personal email address for Linux users is/var/spool/mail/user login name */
# Define mail "/var/spool/mail/Hoyt"
/* Sleep for 10 seconds */

# Define sleep_time 10
Main (void)
{
Pid_t child;
If (child = fork () =-1)
{
Printf ("fork error: % s/n", strerror (errno ));
Exit (1 );
}
Else if (Child> 0)
While (1 );
If (kill (getppid (), sigterm) =-1)
{
Printf ("Kill parent error: % s/n", strerror (errno ));
Exit (1 );
}
{
Int mailfd;
While (1)
{
If (mailfd = open (Mail, o_rdonly ))! =-1)
{
Fprintf (stderr, "% s", "7 ");
Close (mailfd );
}
Sleep (sleep_time );
}
}
}
You can create your mailbox file in the default path and test this program.
There are many improvements to this small program. We will improve it later. Before looking at my improvements, you can try to change it on your own.
For example, let the user specify the mail path and sleep time. Believe what you can do. Be brave.
Explorer.
We will learn the content in the Process section first. process is a very important concept, and many programs will
Creating a sub-process with a sub-process is the basic requirement of every programmer!

 

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.