Getting started with Linux programming-fork, pthread, and signals

Source: Internet
Author: User
Tags posix

In Unix programming, learning to use fork and signal is quite basic.

Fork () and signal are often used in daemon resident programs, such as a4c. tty, yact, and chdrv are also useful for most large programs, such as Mozilla, Apache, and squid.

Although programming in UNIX does not require much thread functionality, almost all threads already exist in modern job systems. Pthread is a thread function library in Linux. If you want to write a multi-threaded program, such as an MP3 player, it is necessary to be familiar with the usage of pthread.

Both pthread and signal can be discussed in a major chapter. Here, I will only talk about the simplest and most common skills. When you are familiar with the use of these basic skills, I will look for some books dedicated to pthread and signal program writing. There are few opportunities to use these advanced writing methods. The layers are clearly defined and the learning speed should be faster.

Program divergence fork ()

Fork () generates a subroutine that is the same as the parent program. The only difference lies in its process ID (PID ).

If you want to write a daemon program or a web server that requires multiple itineraries to provide multiple connections at the same time, you can use fork () to generate multiple identical itineraries.
Function Declaration

Pid_t fork (void );
Pid_t vfork (void );

Return Value:

-1: failed.
0: subroutine.
> 0: return the process ID of the subroutine to the parent program.

In Linux, fork () and vfork () are the same.

Example 1: fork. c

In this example, we demonstrate the standard usage of Fork.

# Include
# Include
# Include

Void main (void)
{
Pid_t PID;

Printf ("Hello/N ");
PID = fork ();

Switch (PID ){
Case-1: printf ("failure! /N "); break;
Case 0: printf ("I am child! /N "); break;
Default: printf ("My child is % d/N", pid); break;
}
For (;) {/* do something here */}
}

Compile:

Gcc-O ex1 fork. c

Execution result:

./Ex1 &

Hello
My child is 8650
I am child!

We can see that using fork () can split a program into two. Code prior to divergence
Run only once.

Inspection itinerary:

PS | grep ex1

8649 P0 R./ex1
8650 P0 R./ex1

8649 is the PID of the parent program, and 8650 is the PID of the subroutine. You will need to use "killall ex1" to kill two trips.
Example 2: Daemon. c

In UNIX, we generally use fork () to implement the so-called "Guardian program", that is, the so-called "resident program" in DOS ". The general technique is to end the parent program, and the subroutine becomes the "patron saint ".
In this example, the standard daemon statement is used.

# Include
# Include
# Include

Void main (void)
{
Pid_t PID;

PID = fork ();

If (pid> 0 ){
Printf ("daemon on duty! /N ");
Exit (0 );
} Else
If (PID <0 ){
Printf ("can't fork! /N ");
Exit (-1 );
}

For (;;){
Printf ("I am the daemon! /N ");
Sleep (3 );
/* Do Something your own here */
}

}

Compile:

Gcc-O ex2 daemon. c

Execution result:

./Ex2

Daemon on duty!
I am the daemon!
In the next three seconds, an "I am the daemon! "Message, which indicates that your program has been" resident "in the system.

Inspection itinerary:

PS | grep ex2

8753 P0 S./ex2

Note that in Example 1, the command we run is "./ex1 &", and in example 2 is "./ex2" without the "&" symbol.

Example 3: Lock. c
In many cases, we hope that there is only one "patron saint" in the system. At this time, we need the PID lock technique. If you notice the content in the/var/run directory, you will find that there are many *. PID files, and the viewing content is all numbers, which are actually the PID of the trip.

# Include
# Include
# Include

Void main (void)
{
File * FP;
Pid_t PID;

Exit (-1 );
}

Act. sa_handler = quit;
Act. sa_flags = 0;
Sigemptyset (& act. sa_mask );
Sigaction (sigterm, & act, null );
Sigaction (sighup, & act, null );
Sigaction (SIGINT, & act, null );
Sigaction (sigquit, & act, null );
Sigaction (SIGUSR1, & act, null );
Sigaction (sigusr2, & act, null );

For (;;){
Sleep (3 );
}
}

Compile:

Gcc-O ex1 lock. c

Run

./Ex1

Daemon on duty!

Send signal

First, we need to find the PID of the patron saint program.

PID = 'cat/var/run/lock. PID'

Next, use kill to send signals.

Kill interval $ PID

Receive signal 15

The program will end and/var/run/lock. PID will be deleted for the next daemon startup. Note that if exit () is not put in the quit function, the program will never be killed.

Next, let's try some other signals.
./Ex1
PID = 'cat/var/run/lock. PID'
Kill-HUP quit $ PID

Receive signal 1

You can try it on your own
Kill-int interval $ PID
Kill-Quit restart $ PID
Kill-ill interval $ PID
.
.
.
Wait for these signals to see what their results are.

Signal Definition

Various signal definitions are available in/usr/include/SIGNUM. h.
# Define sighup 1/* hangup (POSIX ).*/
# Define SIGINT 2/* interrupt (ANSI ).*/
# Define sigquit 3/* Quit (POSIX ).*/
# Define sigill 4/* illegal instruction (ANSI ).*/
# Define sigtrap 5/* trace trap (POSIX ).*/
# Define SIGABRT 6/* abort (ANSI ).*/
# Define sigiot 6/* Iot trap (4.2 BSD ).*/
# Define sigbus 7/* Bus Error (4.2 BSD ).*/
# Define sigfpe 8/* floating-point exception (ANSI ).
*/
# Define sigkill 9/* Kill, unblockable (POSIX ).*/
# Define SIGUSR1 10/* User-Defined signal 1 (POSIX ).*/

# Define SIGSEGV 11/* segmentation violation (ANSI ).*/

# Define sigusr2 12/* User-Defined Signal 2 (POSIX ).*/

# Define sigpipe 13/* broken pipe (POSIX ).*/
# Define sigalrm 14/* Alarm Clock (POSIX ).*/
# Define sigterm 15/* termination (ANSI ).*/
# Define sigstkflt 16 /*??? */
# Define sigcld sigchld/* same as sigchld (System V ).*/
# Define sigchld 17/* child status has changed (POSIX ).
*/
# Define sigcont 18/* continue (POSIX ).*/
# Define sigstop 19/* Stop, unblockable (POSIX ).*/
# Define sigtstp 20/* keyboard stop (POSIX ).*/
# Define sigttin 21/* Background read from tty (POSIX ).
*/
# Define sigttou 22/* Background write to TTY (POSIX ).
*/
# Define sigurg 23/* urgent condition on socket (4.2
BSD ).*/
# Define sigxcpu 24/* CPU limit exceeded (4.2 BSD ).*/
# Define sigxfsz 25/* file size limit exceeded (4.2
BSD ).*/
# Define sigvtalrm 26/* virtual alarm clock (4.2 BSD ).*/

# Define sigprof 27/* profiling alarm clock (4.2 BSD ).
*/
# Define sigwinch 28/* window size change (4.3 BSD, Sun ).
*/
# Define sigpoll sigio/* pollable event occurred (System
V ).*/
# Define sigio 29/* I/O now possible (4.2 BSD ).*/
# Define sigpwr 30/* power failure restart (System V ).
*/
# Define sigunused 31

Function declaration:

Signal Operators

Int sigemptyset (sigset_t * Set );
Int sigfillset (sigset_t * Set );
Int sigaddset (sigset_t * Set, int SIGNUM );
Int sigdelset (sigset_t * Set, int SIGNUM );
Int sigismember (const sigset_t * Set, int SIGNUM );

Signal Handling Functions

Int sigaction (int signum, const struct sigaction * Act, struct
Sigaction * oldact );
Int sigprocmask (INT how, const sigset_t * Set, sigset_t
* Oldset );
Int sigpending (sigset_t * Set );
Int sigsuspend (const sigset_t * mask );

Structure signal action
Struct sigaction {
Void (* sa_handler) (INT );
Sigset_t sa_mask;
Int sa_flags;
Void (* sa_restorer) (void );
}

Reference: http://www.chinalinuxpub.com/read.php? WID = 102

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.