C language programming in Linux-Process Creation

Source: Internet
Author: User

C language programming in Linux-Process Creation

Author: Hoyt

1. Process Concept

The Linux operating system is intended for multiple users. At the same time, many users can issue various commands to the operating system. How does the operating system implement multi-user environments? In modern operating systemsProgramAnd process concepts. So what is a program and a process? In general, a program contains executableCodeIs a static file, and the process is an instance of the program that starts to run but has not ended. It is the specific implementation of the executable file.

A program may have many processes, and each process may have many sub-processes. and generate child processes. after a program is called to the memory by the system, the system allocates certain resources (memory, device, and so on) to the program and then performs a series of complex operations to turn the program into a process for the system to call. in the system, only processes have no programs. to distinguish different processes, the system assigns an ID (like our ID card) to each process for identification.

To make full use of resources, the system also differentiates processes from each other. processes are divided into five states: new, running, blocking, ready, and completed. "New" indicates that the process is being created, "running" means that the process is running, "blocking" means that the process is waiting for an event, and "ready" means that the system is waiting for the CPU to execute the command, completion indicates that the process has ended and the system is recycling resources. for a detailed explanation of the five States of a process, see operating system.

2. Process flag

As we know above that all processes have an ID, how can we get the ID of the process? The system calls getpid to get the ID of the process, while getppid can get the ID of the parent process (the process that creates the process that calls this function.

Pid_t getpid (void );

Pid_t getppid (void );

The process serves the program, and the program serves the user. in order to find the User Name of the process, the system also establishes contact with the user for the process. this user is called the owner of the process. each user also has a user ID. the system calls getuid to obtain the ID of the process owner. because the process uses some resources, and Linux protects system resources, there is a valid user ID to obtain certain resource processes. this ID is related to the usage of system resources and involves process permissions. the system calls geteuid to obtain the valid user ID of the process. the process corresponding to the user ID has a group ID and a valid group ID. The system calls getgid and getegid to obtain the group ID and the valid group ID respectively.

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 and so on). At this time, we can call getpwuid to get it.

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

# Include

Struct passwd * getpwuid (uid_t UID );

 

Next we will learn an example to practice the functions we have learned above:

# Include

# Include

# Include

# Include

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.

Pid_t fork ();

After a process calls fork, the system creates a sub-process. this sub-process is different from the parent process only by its process ID and parent process ID. Others are the same. just like clone itself. of course it makes no sense to create two identical processes. to distinguish Parent and Child processes, we must track the return values of fork.

When the fork fails to be used (the memory is insufficient or the maximum number of processes has reached), fork returns-1. Otherwise, the return value of fork plays an important role. for the parent process fork, return the child process ID, and for the Fork sub-process, return 0. the Parent and Child processes are differentiated based on the returned values.

Why should a parent process create a child process? We have already mentioned that Linux is a multi-user operating system, and many users compete for system resources at the same time. sometimes a process creates a sub-process to compete for resources to complete the task earlier. once a child process is created, the Parent and Child processes run from the fork together to compete for system resources. sometimes we want the sub-process to continue execution, and the parent process is blocked until the sub-process completes the task. in this case, we can call wait or waitpid.

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 there is no parent process, no child process, or its child process has ended, wait will return immediately. wait will return the ID of the sub-process when the sub-process is successful (because the sub-process ends). Otherwise,-1 is returned and the global variable errno is set. stat_loc is the exit status of the sub-process. the sub-process calls exit, _ exit or return to set this value. to obtain this value, Linux defines several macros 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, wait for the specified process (PID ). if the value is 0, wait for any process with the same group ID as the caller's group ID. -1 is equivalent to wait call. wait for any process whose ID is equal to the absolute value of PID when the value is less than-1. stat_loc and wait have the same meaning. options can determine the status of the parent process. two values can be obtained: wnohang: the parent process returns immediately when no child process exists. wuntached: waitpid is returned when the child process ends, but the exit status of the child process cannot be obtained.

After the parent program is created, the sub-program generally needs to execute different programs. To call the system program, we can use the system to call the. exe Class C class to call five functions.

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 []):

The exec invocation can execute a given program. for more information about exec invocation, see the System Manual (manexecl ). next we will learn an example. note that-LM should be added during compilation to connect to the mathematical function library.

# Include

# Include

# Include

# Include

# Include

# Include

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);

}< br>
else if (child = 0)

{< br>
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 );

}< br>
while (CH ILD = 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. Create a daemon

If you have written a program in the DOS era, you may know how much code we need to write a resident memory program in DOS. on the contrary, it is 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 can put a program in the background for execution without writing code. we only need to add the & Symbol shell after the command to put our program to the background for running. here we "develop" A background email check program. this program will go back to check our mailbox at a specified time. If we find that we have emails, we will keep sending alarms (sound through the small speakers on the chassis ). the enhanced version of this function will be available later. background Process Creation idea: first, the parent process creates a child process. then the child process kills the parent process (isn't it heartless ?). All tasks of signal processing are processed by sub-processes.

# Include

# Include

# Include

# Include

# Include

# Include

# Include

/* 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", "\ 007 ");

Close (mailfd );

}

Sleep (sleep_time );

}

}

}

 

You can create your mailbox file in the default path and test this program. of course there are still many improvements to this program. we will improve this small program later. Before looking at my improvement, you can try to improve it on your own. for example, you can specify the mail path and sleep time. believe what you can do. be a brave explorer.

Process is a very important concept. Many programs use sub-processes. Creating 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.