Several Methods for exchanging information between Unix processes using Shell

Source: Internet
Author: User
Tags sigint signal

This article describes how to use the shell language in SCO OpenServer5.0.5 to exchange information between processes:
Use named pipes to exchange information between processes
Use kill and trap statements to exchange information between processes
Use the "." command to exchange information between processes
Use the export Statement to transmit the information of the parent process to the child process
1. Use Named Pipes

A named pipe is a data structure with first-in-first-out/FIFO). It allows two processes to exchange information through pipeline connections. In Unix systems, named pipes are special types of files, so you can perform read and write operations on named pipes. Of course, there are also restrictions on read and write permissions and execution permissions.
The following command creates a named pipe:
/Etc/mknod pipe_name p
"Pipe_name" indicates the name of the named pipe to be created. The parameter p must appear after the named pipe name.
After a named pipeline file is created, some processes can constantly write information to the named pipeline file, while others can constantly read information from the named pipeline file. Read/write operations on named MPs queue files can be performed simultaneously. The following example shows the workflow of the named pipeline.
The programs running in processes A, B, and C are just A simple echo command that constantly writes information to the named pipeline file/tmp/pipe1. At the same time, the "read msg" command in the program constantly reads this information from the named pipeline file/tmp/pipe1, so as to exchange information between these processes.
During program execution, the named pipeline file is created first, and the program is in the waiting state until A process in process A, B, and C writes information to the named pipeline. You can use the rm command to delete the named pipe file to clear the configured named pipe.
The following is an example of recording attendance:
The program/tmp/text running on the host generates the named pipe/tmp/pipe1 and keeps reading information from the Named Pipe for display on the screen.
/Tmp/text program:
If [! -P/tmp/pipe1]
Then
/Etc/mknode/tmp/pipe1 p
Fi
While:
Do
Read msg
If ["$ msg" = ""]
Then
Continue
Else
Echo "$ msg"
Fi
Done </tmp/pipe1
The employee sign-In program/tmp/text1 is run on the terminal. Each employee typed his/her name or code on any terminal, and the program/tmp/text1 sent the name along with the time of signing to the name pipeline.
/Tmp/text1 program:
Tty = 'Who am I | awk' {print $2 }''
While:
Do
Echo "Enter your name: \ c">/dev/$ tty
Read name
Today = 'date'
Echo "$ name \ t $ today"
Done>/tmp/pipe1
After an employee enters his/her name on the terminal, the host running the/tmp/text program will display the following results:
Wang Thu Jan 28 09:29:26 BTJ 1999
He Thu Jan 28 09:29:26 BTJ 1999
Cheng Thu Jan 28 09:30:26 BTJ 1999
Zhang Thu Jan 28 09:31:26 BTJ 1999
Ii. Use the kill command and trap statement

In Unix systems, when an abnormal internal status is detected, or the hardware and external devices send requests, or execute certain commands, an event is reported to the processes in the system. After the process captures these signals, the system will execute preset default programs to complete the specified actions. These preset default programs are called signal system traps.
In shell, use the trap statement to set a new trap for the signal. Except for the mail number 11 when the shell captures a signal, because the shell itself needs to use this signal for memory allocation ), it transmits this signal to all program parent programs and subprograms that are currently being executed) and executes the signal traps set in parent programs and subprograms respectively. Once the execution of the trap program ends, the system returns to the center breakpoint and continues to execute the original program process.
The basic format of the trap statement:
Trap command_list signal_list
Command_list: a command list composed of one or more commands or command groups. When the command list contains multiple commands, they must be enclosed in single or double quotation marks and separated by semicolons.
Signal_list: A list of signals composed of one or more signal values. Each signal value must be separated by a space.
Resetting the signal trap in a shell program parent program does not change the trap of the same name signal in the subroutine called by this program. Similarly, the signal traps set in subprograms do not affect the signals with the same name in the parent program.
When shell reads the trap statement, it needs to scan the command list once to set the trap. After capturing the signal, shell scans the command list again and runs the configured trap program command or command group ). Therefore, if the command list contains a variable replacement or command replacement expression, shell replaces the expression with the current variable value or command result when scanning the command list for the first time, so that when the trap program is executed while the signal is captured, the trap program is no longer the originally set trap program. To avoid this, use single quotes instead of double quotes to enclose the command list containing variable replacement or command replacement expressions in the trap statement. Because single quotes can eliminate the special meaning of all characters, this prevents shell from performing any replacement or replacement operations during the first scan until the command list is executed.
There are many signal transmission methods to a program or process. For example, pressing Ctrl + c or Del during program execution will send a SIGINT signal to the program, system traps that execute this signal will terminate program execution. Using the kill command to transmit signals is the most common method in shell programming.
The basic format of the kill command is:
Kill [-signal] PID
Generally, the kill command is used to terminate a process. However, if a signal with a hyphen "-" is used as a parameter, the kill command sends the signal to one or more processes indicated by the PID, rather than terminating the process. When the trap statement captures this signal, it executes the set signal trap program to implement inter-process communication.
The following example shows how to use the signal mechanism to implement mutual communication between the master and slave1 and slave2 programs. First, run the slave1 and slave2 programs in the background, and then run the program master. The process numbers of the three programs are recorded in the/tmp/pro_list file.
The program slave1 first sets the trap of signal 15, and then writes its current process to the file/tmp/pro_list. After obtaining the master process number, it enters the cyclic state. When receiving the signal 15 from the master, execute the trap program and display the relevant information, then send a signal 15 to the master.
The execution of the slave2 program is similar to that of slave1.
The program master first sets the trap of signal 15, and then writes its current process to the file/tmp/pro_list. After obtaining the process numbers of all the slave programs, send a signal of 15 to these slave programs and wait cyclically. When receiving the signal 15 from slave1 or slave2, execute the trap program, display the relevant information, kill all slave processes, clear the file/tmp/pro_list, and then exit.
Program/tmp/slave1:
Slave (){
Echo "slave1 has received sighal from master"
Echo "Request master to kill slave1 process"
Kill-15 $ master_pid
}
Trap slave 15
Echo "slaveacropid $">/tmp/pro_list
Sleep 1
While:
Do
Master_pid = 'awk' $1 ~ /Master/
{Print $2} '/tmp/pro_list'
If ["$ master_pid "! = ""]
Then break
Fi
Done
While:
Do
Sleep 1
Done
Program/tmp/slave2:
Slave (){
Echo "slave2 has received sighal from master"
Echo "Request master to kill slave2 process"
Kill-15 $ master_pid
}
Trap slave 15
Echo "slave2_pid $">/tmp/pro_list
Sleep 1
While:
Do
Master_pid = 'awk' $1 ~ /Master/
{Print $2} '/tmp/pro_list'
If ["$ master_pid "! = ""]
Then break
Fi
Done
While:
Do
Sleep 1
Done
Program/tmp/master:
Kill_slave (){
Echo "Master has received ed signals
From slave processes"
Echo "End all slave processes"
Kill-9 $ slave_list
>/Tmp/pro_list
Exit 0
}
Trap kill_slave 15
Echo "master_pid $">/tmp/pro_list
Sleep 1
Slave_list = 'awk' $1 ~ /Slave/
{Print $2} '/tmp/pro_list'
Echo "Current slave processes are :"
Echo "$ slave_list"
Kill-15 $ slave_list
While:
Do
Sleep 1
Done
Execution program:
$ Cd/tmp
$./Slave1 &
15638
$./Slave2 &
16831
$./Master
Current slave processes are:
15638
16831
Slave1 has received signal 15 from master
Request master to kill slave1 process
Slave2 has received signal 15 from master
Request master to kill slave2 process
Master has received signals from slave processes
End all slave processes
15638 Killed
16831 Killed
$
3. Run "."

"." Is an internal shell command. It reads all command statements from the specified shell file and runs them in the current process. Therefore, when multiple shell process Parent and Child processes or unrelated processes can share a set of variable values, you can define these variable assignment statements into a shell file, and use the dot statement in the program that requires these variable values to reference this shell file, so that variable values can be shared. modifications to these variable values only involve this shell file ). Note that the shell file cannot contain statements containing location parameters, that is, it cannot accept command line parameters such as $1 and $2.
The following is a sample procedure for publishing daily commodity prices in supermarkets. The program/tmp/jiage is responsible for releasing the daily product prices. It assigns values to each product price and writes the corresponding value assignment statement to the file/tmp/jiagebiao. The receiving program/tmp/shoukuan running on each terminal reads all the value assignment statements in the file/tmp/jiagebiao and runs them in the current process, to get the price set in the Program/tmp/jiage.
Price Setting Program/tmp/jiage:
Echo "Enter the price of chicken,
Duck and fish: \ c"
Read chicken duck fish
Exec 3>/tmp/jiagebiao
Echo "chicken_price = $ chicken"> & 3
Echo "duck_price = $ duck"> & 3
Echo "fish_price = $ fish"> & 3
After the/tmp/jiage program is executed, the file/tmp/jiagebiao contains the following content:
Chicken_price = 5.4
Duck_price = 2.5
Fish_price = 4.2
Receiving Program/tmp/shoukuan:
./Tmp/jiagebiao
Count = 0
While:
Do
Echo "Enter the trade name and
Quantities or input q to sum: \ c"
Read trade $ count quantity $ count
Eval a =\$ trade $ count
If ["$ a" = "q"]
Then if [$ count-gt 0]
Then
Count = 'expr $ count-1'
Fi
Break
Fi
Count = 'expr $ count + 1'
Done
Echo "\ n 'date '"
Echo "trade name \ tquantity \ tsum"
While ["$ count"-ge 0]
Do
Eval trade = "\ $ {trade $ count }"
Eval trade_price = "$ {trade} _ price"
Eval danjia =\\ {$ trade_price}
Eval quantity = "\$ {quantity $ count }"
Sum = 'echo "scale = 2; $ danjia
* $ Quantity "| bc'
Echo "$ trade \ t $ quantity \ t $ sum"
Count = 'expr $ count-1'
Done
Execute the program/tmp/shoukuan on the terminal and display it as follows:
Enter the trade name and quantities
Or input q to sum: chicken 2
Enter the trade name and quantities
Or input q to sum: fish 3
Enter the trade name and quantities
Or input q to sum: duck 4
Enter the trade name and quantities
Or input q to sum: q
Thu Jan 28 09:29:29 BJT 1999:
Duck 4 10
Fish 3 12.6
Chicken 2 10.8
4. Use the export Statement

Generally, a shell variable is a local variable. Whether it is a value assignment operation or a value assignment by command, its variable value is only valid in the current process. However, the shell variable described in the export Statement becomes a global variable, and its variable name and variable value can be passed to the child process and its child process. The value of this variable can be modified in the child process, but it does not affect the value of this variable in the parent process.
In the following example, the parent process/tmp/text) passes the assigned variable pro_name to the child process/tmp/text_child ), the new value assigned to the variable pro_name in the child process does not affect the value of the variable in the parent process.
/Tmp/text program:
Pro_name = "PARENT"
Echo "The variable pro_name is
$ Pro_name in parent process"
Export pro_name
/Tmp/text_child
Echo "The variable pro_name is
$ Pro_name after retund to parent process"
/Tmp/text_child program:
Echo "The variable pro_name ($ pro_name) is
Transmited to child process"
Pro_name = "CHILD"
Echo "To change the variable pro_name
$ Pro_name in child process"
Execute the program/tmp/text:
$/Tmp/text
The variable pro_name is PARENT in parent process
The variable pro_name (PARENT)
Is transmited to child process
To change the variable pro_name to CHILD in child process
The variable pro_name is PARENT after retund to parent process
$


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.