I. Features of multi-process procedures Because the UNIX system is a module multiple user system, the CPU is assigned to each user by time, and it should be used in essence to be used to use the CPU to all process, each process has its own The operating environment allows "Semi-finished Products" that has been "forgotten" when the CPU is switched, and the process of "semi-finished products" is calculated in DOS. The process of switching is a "DOS Interrupt" processing process, including three levels. : (1) Saving of user data: including the main segment (Text), Data Section (DATA, BSS), Stack, Shared Memory, Save: Save of Register Data: including PC (Program Counter, pointing to the address of the instruction to be executed), PSW (Processor Status Word, Processor Word), SP (Stack Pointer, Stack Pointer), PCBP (Pointer Of Process Control Block, Process Control Block Pointer), FP (Frame Pointer, pointing to the first address of a Local variable of a function in the stack), AP (AUGUMENT POINTER, pointing to the function called in the stack), ISP (Interrupt Stack Pointer, interrupt stack pointer), and other universal registers Wait. (3) System hierarchical preservation: including Proc, U, Virtual Storage Space Management Table, Interrupt Processing Stack. For this process, it can run normally when the CPU time film is obtained. Since the system has handled all of these interrupt processing The process, what else do we have to worry? We can use the multi-process feature provided by the system, let several programs work together, simply and efficiently give it a result. In addition, UNIX system itself It is also a multi-process program written in c language. Multi-process programming is the characteristics of UNIX. When we are familiar with multi-process programming, there will be a deeper understanding of the UNIX system mechanism. First, I will introduce some of the multi-process programs. Features: 1. One complicated event is to decompose into a number of simple events, which has formed this concept in the brain of the programmer, first breaking the problem into a small problem, will The small problem is subdivided, and finally makes a function on a suitable scale. It is also said in the software engineering. If we think about the way, some small problems can not interfere with each other, you can Processing, and in a key point, you need to be unified in one place, so the operation of the program is parallel, at least from the person's time concept. And the calculation of each small problem is more simple. Single. 2. Simple and orderly procedures are not sub-management of programmers, and the programmer is designed for each process and combines them with a certain communication mechanism. The design of each process is simple, only carefully cope with the total control section (in fact, it is also quite simple), it can complete the construction of the entire program. 3. Mutual interference This feature is the characteristics of the operating system, each process is independent. No criterion. 4. Serving, for example, in a data phone query system, design the program to a process only to handle one query, complete a transaction. When the phone query begins, it is generated to deal with this Supper query; when another phone comes in, the master program produces such a process to deal with it. Each process has disappeared after completing the query task. This programming is simple, as long as you do a query program, you can use more Process programming system call 1.fork () function: Create a new process. Syntax: #include #include pid_t fork ();
Note: This system calls generates a new process, a sub-process, a replica called a process. Calling process is called the father process, the child process inherits almost all the properties of the parent process:. Real UID, GID, and valid UID, GID.. Environment variable. Additional gid.. Close sign when calling EXEC (). UID Setting the mode bit. The GID set the pattern bit. The process group number...... Directory.. The root directory.. File creates a mask umask.. File length limits ulimit. The sub-process also has different properties different from the parent process:. Process number, child process number different from the process group number with any activity. Parent process number. Child process inherits the file descriptor or flow of the Parent process, Copy and share this resource with the parent process and other child processes. The user time and system time of the child process are initialized to 0.. The timeout clock of the child process is set to 0.. The signal processing function pointer of the child process is empty. The child process does not inherits the record lock of the Parent process. Return Value: Returns the child process back to the child process, returning the child process number for the parent process, which is the most convenient way to distinguish the parent-child process. Return -1 The parent process, the child process does not generate. Example: PID_T PID; IF ((PID = fork ())> 0) {/ * Parent Process Process * /} Else If (PID == 0) {/ * child process processing process * / EXIT (0); / * CEO must use exit () to exit running * /} else {printf ("fork error / n"); exit (0);} 2.system () function: generate a new The process, the child process executes the specified command. Syntax: #include #include int system (string) Char * string; Description: This call passes the parameter string to a command interpreter (typically SH) execution, that is, String is explained as A command is executed by the SH. If the parameter string is an empty pointer to check the command interpreter existing. This command can be the same as the command line command, but because the command is placed in the system call, you should pay attention to the system call. The processing of the special meaning character is compiled. The lookup of the command is defined by the PATH environment variable. The consequences of the commands generated generally not affect the parent process. Return Value: When the parameter is an empty pointer, only when the command interpreter Be effective The return value is non-zero. If the parameter is not an empty pointer, the return value of the return value is the return value of the command (with WaitPID ()) return value. The command is invalid or the syntax error returns a non-zero value, and the command executed is terminated. Other The situation returns -1. Example: char command [81]; int i; for (i = 1; i <8; i ) {Sprintf (Command, "PS -T TTY% 02i", I); System (Command) } 3.exec () function: Perform a file syntax: #include int execl (path, arg0, ..., argn, (char *)) char * path, * arg0, ..., * argn; int Execv (Path, Argv) Char * Path, * Argv []; int execle (path, arg0, ..., argn, (char *) 0, envp) char * path, * arg0, ..., * argn, * envp []; int execve (path, argv, envp) char * path, * argv [], * envp []; int execvp (file, argv) char * file, * argv []; description: This is a system The invocation family is used to transfer a new program to the memory occupied by the process, and overwrite, generating a new memory process image. The new program can be an executable or shell batch command. When the C program is executed , Is called: main (int Argc, char * argv [], char * envp [];
Argc is the number of parameters. Each parameter string pointer array, ENVP is a pointer array of environment variable strings for the new process. Theargc is at least 1, argv [0] is the program file name, so the EXEC system called family In the path name of the new process file, File is a new process file name. If File is not a full path name, the system call will automatically find the corresponding executable file to the corresponding executable file. If the new process file is not an executable The target file (such as a batch file), EXECLP () and execv () will form the file content as a standard input of a command interpreter to form system (). Arg0, ... and other pointer points to the end of '/ 0' ending The string, the active parameters of the new process, and the parameter list ends with an empty pointer. In turn, Arg0 must exist and point to the new process file name or path name. Similarly, Argv is a string pointer array, argv [0] pointing The new process file name or path name, and ends with an empty pointer. ENVP is a string pointer array, ending with an empty pointer, which forms a new process environment. The file opened before calling these system calls to the new process. It is also open, unless it has defined a Close-ON-EXEC flag. Opened file pointer remains unchanged in the new process, all related file locks are also reserved. Calling process settings and being captured The process is restored to default settings, and the other remains unchanged. When the new process starts, press the UID and GID of the SUID and SGID settings definition files for the file to be valid UID and GID. The new process also inherits the following properties:. Additional GID Process number.. The process group number. Control terminal.. ALARM clock signal remains. The current work directory.................................. User time, system time, child process user time, child process system time. Record lock. Process signal mask.. Signal mask.. Priority.. For schedule. After the call is successful, the system calls to modify the new process file The latest access time. Return value: The system call generally does not have successful return values, because the original process has waters. Example: Printf ("Now this process will be ps command / n"); Execl ("/ bin / ps "," ps "," - ef ", null; 4.popen () function: Initialize the pipeline from / to a process. Syntax: #include file * pop # (Command, Type) Char * Command, Type; Explanation: This system call is invoked. Cheng and the executed command creates a pipe. The parameter command is the command line that is executed as an I / O mode, "R" is read from the executed command, "W" is written to the executed command. Return one The standard stream pointer, as a pipeline descriptor, read or write data to the executed command (STDIN or STDOUT as executed command) The system call can be used to call the system command in the program, and obtain the output information of the command or Command Enter information. Return Value: Returns NULL: Return to NULL, returns the file pointer of the pipe. 5.pclose () Features: Close the pipeline of a process. Syntax: #include int pclose (strm) file * strm; Description: This system calls to turn off the pipe opened by popN (), and wait for the command to perform the end of the command to turn off the command return code after the pipe is turned off. Return Value: If the file descriptor is not turned off is not from POPEN Open, returns -1. Example: Printf ("Now this process will call popen system call / n"); file * fd; if ((fd = POPEN ("PS-Ef", "R")) = = NULL) {Printf ("Call Popen Failed / N"); Return;} else {char STR [80]; While (FGETS (STR, 80, FD)! = NULL) Printf ("% s / n", STR } PCLOSE (FD);
6.wait () function: Wait a child process to return and modify the status syntax: #include #include pid_t wait (stat_loc) int * stat_loc; Description: Allow the status information of the process to get the child process. The calling process will hang up until it A child process termination. Return value: When a child process returns, the return value is the sub-process number, otherwise the return value is -1. At the same time, the return value of the STAT_LOC returns the sub-process. Example: / * Parent Process * / if Fork ()> 0) {WAIT ((int *) 0); / * Parent process waiting for the sub-process return * /} else {/ * child process processing * / exit (0);} 7.waitpid () function : Waiting for the sub-process of the specified process number and modify the status syntax: #include #include pid_t waitpid (PID, STAT_LOC, OPTIONS) PID_T PID; INT * STAT_LOC, Options; Description: When PID is equal to -1, Options is equal to 0, The system call is equivalent to Wait (). Otherwise, the behavior of the system call is determined by the parameters PID and Options. PID specifies a group of parent processes that require the child process to know its status: -1: Requires the return status of any child process. > 0: The state of the child process is required to know the process number is the status of the child process of the PID value. <-1: Requires the status of the child process in which the process group number is the absolute value of the PID. The Options parameter is a sign indicated by a bit method or composed. Bitmap, each flag is represented by a bit ratio 1 in bytes: Wuntraced: Reports any sub-process of any unknown and has stopped running the specified process number. The status of the sub-process has not been Reported. Wcontinued: Reports any sub-process of the specified process number that continues to run, the status of the child has not been reported from continuing to run. WHOHANG: When calling this system call, specify the sub-process of the process number The status is not immediately valid (ie, can be read immediately), call the process and suspend execution. Wnowait: Keep the process of setting its status in the STAT_LOC in the waiting state. The process will wait until next time Return the status value. Return value: When a child process returns, the return value is the sub-process number, otherwise the return value is -1. At the same time, the return value of the STAT_LOC returns the sub-process. Example: PID_T PID; int Stat_loc; / * Father Process * / if ((pID = fork ())> 0) {WaitPid (PID, & stat_loc, 0); / * Parent process Waiting for the sub-process of the process number to PID * /} Else {/ * child process processing process * / exit (1);} / * parent process * / printf ("stat_loc is [% d] / n", stat_loc ); / * String "STAT_LOC IS [1]" will be printed * / 8.SetPGRP () function: set process group number and session number. Syntax: #include pid_t setpgrp () Description: If the callout process is not the same Process. Set the process group number and the session number to the process number equal to it. And release the control terminal of the transfer process. Return value: After the call is successful, return new process group number. Example: / * Parent Processing * / IF (fork ()> 0) {/ * Parent Processing * /} else {setpgrp (); / * The process group number of the child process has been modified to be the same * / exit (0);} 9. Exit () function: Termination process. Syntax: #include void exit (status) int stat:: The calling process is terminated by the system call. Cause additional processing ends before the process is terminated before the process is terminated. Return Value: None 10. Signal ) Function: Signal management function syntax: #include void (INT) INT SIG; Void (* DISP) (int); void (* Sig, Disp)) (int) INT SIG void (* DISP) (int); int Sigrelse (SIG) INT Sig; int Sigignore (SIG) INT SIG
INT Sigpause (SIG) INT SIG; Description: These system calls provide a simple signal processing for the application to specify the specified signal. Signal () and SIGSET () are used to modify the signal positioning. Parameter SIG Specify the signal (except sigkill and sigstop, this Both signals are processed by the system, the user program cannot be captured. DISP specifies a new signal positioning, that is, a new signal processing function pointer. Can be SIG_IGN, SIG_DFL or signal handle address. If SIGNAL (), DISP is a signal handle address When SIG does not receive this signal for SIGILL, SIGTRAP, or SIGPWR, the system first resets the SIG signal handle as SIG_DFL, then executes the signal handle. If SIGSET (), the DISP is the signal handle address, the signal, the system First, add this signal to the signal mask of the calling process, then execute the signal handle. After the signal handle runs, the system will recover the signal mask of the calling process to receive the preamble. In addition, when using sigset (), The DISP is SIG_HOLD, then the signal will join the signal mask of the calling process and the signal is positioned unchanged. Sighold () adds the signal to the signal mask of the calling process. Sigrelse () Signal from the signal mask of the signal from the calling process Delete. SIGIGNORE () Sets the positioning of the signal to SIG_IGN. Sigpause () Remove the signal from the calling process of the calling process, and hangs the calling process until the signal is received. If the signal SIGCHLD is positioned as SIG_IGN, then call The child process of the process will not turn into a zombie process during termination. The calling process does not have to wait for the child to return and do the appropriate processing. Return Value: Signal () Returns the value of the DISP recently called Signal () setting. Otherwise SIG_ERR. Example 1: Set the user's own signal interrupt processing function, as an example: int flag = 0; void myself () {flag = 1; Printf ("get signal sigint / n"); / * To re- Setting the SIGINT signal interrupt processing function to perform this function with * Next * / void (* a) (); a = myself; Signal (Sigint, A); Flag = 2;} main () {while (1) { Sleep (2000); / * Wait for interrupt signal * / if (flag == 1) {Printf ("Skip System Call Sleep / N"); exit (0);} if (Flag == 2) {Printf ("Skip System Call Sleep / N); Printf (" Waiting for Next Signal / N ");}}} 11.kill () function: Send a signal to one or set of processes. Syntax: #include # INCLUDE INT KILL (PID, SIG); PID_T PID; INT SIG; Description: This system call sends a signal to one or set of processes, which is specified by the parameter SIG, one of the signal tables given by the system. 0 (empty signal) checks the error but actually does not send the signal to check the validity of the PID. PID specifies the process or process group to be sent to the signal. If it is more than 0, the signal will be sent to the process number equal to PID process; if the PID is equal to 0 signals will be sent to all processes with the send signal process in one process group (except for special processes of the system); if the PID is less than -1, the signal will be sent to all process groups. The same process as the absolute value of the PID;
If the PID is equal to -1, the signal will be sent to all processes (except for special system processes). The signal must be sent to the specified process, first call the process must have the right to send signals to the process. If the process is suitable for appropriate priority The level has permission. If the actual or valid UID of the process is equal to the actual UID of the process of the received signal or use the setUID () system call setup settings, or SIG is equal to the session number of the two parties while transmitting and receiving the same number, then call the process. There is also permission to send a signal. If the process is sent to any one of the processes specified by the process to the PID, call success, otherwise the call failed, no signal is issued. Return Value: Return 0, otherwise return -1. Example: Assumption An example process number 324, now send a Sigint signal, let it perform signal processing: Kill ((PID_T) 324, SIGINT; 12.Alarm () function: Set a process of timeout clock. Syntax: #include unsigned INT ALARM (SEC) Unsigned INT Sec; Description: The timeout clock indicating the calling process Sends a SIGALRM signal to the calling process after the specified time. Setting the timeout clock time value will not be placed in the stack, and the next setting will put before One (not until the timeout time) is rushed away. If the sec is 0, cancel any previously set timeout clock. Fork () will initialize the timeout clock of the new process to 0. When a process is called using an Exec () system call When the new execution file, the timeout clock set before call is still valid after the call. Return value: Return to the last set timeout clock to the time of the time left, the number of times remaining, the number of times: int flag = 0; void myself () { Flag = 1; Printf ("Get Signal SigalRM / N"); / * To reset the SIGALRM signal interrupt processing function is this function * below * / void (* a) (); a = myself; sIGNAL SIGALRM, A); FLAG = 2;} main () {alarm (100); / * 100 seconds post timeout interrupt signal * / while (1) {SLEEP (2000); / * Waiting for interrupt signal * / if (flag == 1) {Printf ("Skip System Call Sleep / N"); EXIT (0);} IF (Flag == 2) {Printf ("Skip System Call Sleep / N"); Printf ("Waiting for Next Signal / N ");}}} 1 3. msgsnd () function: Send a message to the specified message queue. Syntax: #include #include #include int msgsnd (msqid, msgp, msgsz, msgflg) int msqid; void * msgp; size_t msgsz; int msgflg; Description: Send a message to the message queue that specifies the message queue identification number by msqid. Parameter MSGP points to a user-defined buffer, and the first domain of the buffer should be long integer, specify the message type, and other data is placed in the buffer. In other textures in the message. Below is the message element definition: long mtype; char mText []; mtype is an integer for receiving the process selection message type. MTEXT is any text of the MSGSZ byte, parameter msgsz can 0 to the system allowed to change. MSGFLG Specifies the action behavior:. If (MSGFLG & IPC_Nowait) is true, the message is not sent immediately and the calling process will return immediately. If (MSGFLG &
IPC_nowait is not true, the calling process will hang up until one of the following occurs: * The message is sent out. * Message Queue Sign is deleted by the system. The system call returns -1. * Call process receives an unloaded Interrupt signal, the calling process continues to execute or terminated. After the call is successful, the relevant structure corresponding to the specified message queue does the following action:. Message number (MSG_QNUM) plus 1. Message Queue Recently Send Process No. (MSG_LSPID) to call the process No.. Message Queue Send Time (MSG_stime) Change to the current system time. The above information can be seen by command ipcs -a. Return Value: Return 0, otherwise returns -1. 14.msgrcv () function: from the message queue Get the message of the specified type. Syntax: #include #include #include int MSGRCV (MSQID, MSGP, MSGSZ, MSGTYP, MSGFLG) INT msqid; void * msgp; int msgsz; long msgtyp; int msgflg; Description: This system call from A message in the message queue specified by MSQID is read from the MSGTYP specified type of message to the buffer pointed to by MSGP, and the structure of the buffer is as previously described, including message type and message body. msgsz is a received message The number of bytes of the body. If the length of the received message body is greater than Msgsz, it will be truncated to the msgsz byte (when the message flag msgflg & msg_noerror is true), the cut-off part will be lost, and not notify the message Send process. MsgTyP Specifies the message type:. Take the first message in the message queue. The first type of MSGTYP in the message queue is received. The first type in the receiving message queue is received in the message queue. The value is not less than the MSGTYP absolute value and the type value and the smallest message. MSGFLG Specifies the operation behavior: if (MSGFLG & IPC_Nowait) is true, the calling process will return immediately. If the message is not received, the return value is -1, errno is set to eNomsg If (MSGFLG & IPC_NOWAIT) is not true, the calling process will hang up until one of the following occurs: * The type of message in the queue is valid. * Message Queue Sign is deleted by the system. System call returns -1. * The calling process receives an unloaded interrupt signal, the calling process continues to execute or terminated. After the call is successful, the relevant structure corresponding to the specified message queue does the following action:. Message (MSG_QNUM) minus 1. Message Queue recently received recently Process number (MSG_LRPID ) Change to the process number. Message queue receiving time (MSG_rtime) is changed to the current system time. The above information can be seen by the command ipcs -a. Return Value: The return value is equal to the number of bytes that receive the actual message body. Uncomfortable returns -1. 15.msgctl () function: Message control operation syntax: #include #include #include int msgctl (msqid, cmd, buf) int msqid, cmd; struct msqid_ds * buf; Description: This system call is provided A series of messages control operations, the operation action is defined by the CMD. The following CMD definition value indicates the definition of each operating action. IPC_STAT: places the current value of each element in the data structure related to the MSQID into the structure pointed to by BUF.. IPC_set : Set the following elements in the data structure related to the MSQID to the corresponding value in the structure points to the BUF. Msg_perm.uid msg_perm.gid msg_perm.mode msg_qbytes This command can only be equal by the effective UID equal to the process of MSG_Perm.cuid or MSG_Perm.uID Or the process of effective UID has appropriate permissions. Only users with appropriate privileges can increase the value of MSG_QBytes. IPC_rmid: Delete the message queue indicated by MSQID. Delete it from the system and destroy the relevant data structure. This command can only Proceedings that are equal to MSG_Perm.cuid or MSG_Perm.cuid or MSG_Perm.UID, have appropriate permissions. Return Value: The return value is 0, otherwise the -1. 16.msgget () function: get a message queue Syntax: #include #include #include int msgget (key, msgflg) Key_t key; int msgflg;
Note: This system calls return the identifier of the message queue associated with the parameter key. If the following fact is established, the identifier and data structure associated with the message queue will be created:. If the parameter key is equal to IPC_Private.. If the parameter key is not An existing message queue identifier is related to it, and the value (MSGFLG & IPC_CREAT) is true. When the message queue is created, the data structure associated with the new message queue identifier will be initialized as follows:. MSG_Perm.cuid and MSG_Perm.uID Set to the valid UID of the process.. Msg_perm.cgid and msg_perm.gid are set to the valid GID of the calling process.. MSG_Perm.Mode Access bit is set to MSGFLG access ratio.. MSG_QNUM, MSG_LSPID, MSG_LRPID, MSG_stime, MSG_RTIME Set to 0.. Msg_ctime is set to the current system time. Msg_qbytes is set to the maximum value allowed by the system. Return Value: Returns a non-0 value, called a message queue identifier; otherwise the return value is -1. Example: In this case, the system calls that include all message queues described above: #define rkey 0x9001L / * read message queue KEY value * / #define WKey 0x9002L / * write message queue's key value * / #define msgflg 0666 / * message queue Access Permissions * / #Define IPC_Wait 0 / * Wait Wait Wait Do not define * / int RMSQID; / * read message queue identifier * / int WMSQID; / * write message queue identifier * / struct msgbuf {long mtype; charc @ 写MTEXT [200];} BUF; / * If you have the identifier where the read message queue already exists, you create and acquire the identifier * / if ((rmsqid = msgGget (ipc_creat)) <0) {Printf ( "Get Read Message Queue"); EXIT (1);} / * If the write message queue already does fail, if there is no existence, create and acquire the identifier * / if ((WMSQID = msgget (WKEY, MSGFLG | IPC_CREAT | IPC_TRUNC)) <0) {Printf ("Get Write Message Queue Failed / N); EXIT (2);} / * Receive All Type Message * / IF (MSGRCV (RMSQID, & BUF, SIZEOF (Long), 0L, IPC_Wait> 0) Printf ("Get% LD Type Message from Queue:% S / N", BUF. MTYPE, BUF.MTEXT; Else {Printf ("Get Message Failed / N"); EXIT (3);} buf.mtype = 3L IF (MSGSND (WMSQID, & BUF, SIZEOF (Struct Msgbuf) -sizeof (long), IPC_nowait)> 0) Printf ("Send Message OK / N"); Else {PrintF ("Send Message Failed / N"); EXIT (4);} MSGCTL (WMSQID, IPC_RMID, (Struct Msqid *) NULL); 17 . SHMAT () Function: Connect the shared memory operation. Syntax: #include #include #include void * shmat (shmid, shmaddr, shmflg) int shmid; void * shmaddr; int shmid;
Description: Connect the shared memory indicated by the SHMID to the data segment of the calling process. The join segment is placed at the address, which is specified by the following criteria: If ShmAddr is equal to (VOID *) 0, the segment is coupled to the system selected by the system The first available address. If ShmAddr is not equal to (void *) 0, the segment is coupled to the address given by (shmaddr% shmlba)).. If ShmAddr is not When equals (void *) 0, the paragraph is coupled to the address specified by ShmAddr. If the (shmflg & sshm_rdonly) is true and the calling process is read, it is read-only; otherwise, if The value is not true and the process is read or written, and the connection is readable. Return Value: Returns the starting address of the connected shared memory segment on the data segment if the call is successful. Otherwise the return value is -1. 18.shmdt () function: Disconnect shared memory joints. Syntax: #include #include #include void * shmdt (shmdt) Void * shmaddr; Description: This system call will be called from the shared memory segment specified by ShmAddr The data segment of the process is out. Return value: If the call is successful, the return value is 0, otherwise the return value is -1. 19.Shmget () function: Get shared memory segment syntax: #include #include #include int shmget (key, Size, shmflg) Key_T key; Int size, Shmflg; Description: This system calls Returns key-related shared memory identifiers. Shared memory identifiers and related data structures and at least size bytes shared memory segments can be created normally, requiring the following facts Established:. Parameter key is equal to IPC_Private. The parameter key does not have a related shared memory identifier, and the "SHMFLG & IPC_CREAT) value is true. When the shared memory is created, the newly generated shared memory identification related data structure is initialized as follows: SHM_PERM.CUID And SHM_PERM.UID is set to the valid UID of the call process. SHM_PERM.CGID and SHM_PHM.GID are set to the valid GID of the calling process. SHM_PERM.MODE Access ratio is set to the SHMFLG access ratio.. SHM_LPID, SHM_NATTCH, SHM_ATIME SHM_DTIME is set to 0.. SHM_CTIME settings Before system time. SHM_SEGSZ is set to 0. Return Value: Returns a non-0 value if the call is successful, referred to as a shared memory identifier, otherwise the return value is -1. 20.SHMCTL () function: Shared memory control operation. Syntax : #include #include #include int shmctl (shmid, cmd, buf) int shmid, cmd; struct shmid_ds * buf; Description: This system call provides a series of shared memory control operations. The operation behavior is specified by CMD. The following is the effectiveness of CMD Value:. IPC_STAT: Put the current value of each element in the data structure related to the SHMID in the structure pointed to by the BUF.. IPC_set: Set the following elements in the SHMID to the corresponding value in the structure pointed to by the BUF . SHM_PERM.UID SHM_PERM.GID SHM_PERM.MODE This command can only be operated by a valid UID equal to the process of SHM_PERM.CUID or SHM_PHM_PERM.UID or a valid UID. IPC_rmid: Delete Shared Memory indicated by the SHMID. Delete and destroy the associated data structure from the system. This command can only be operated by a valid UID equal to the process or effective UID of SHM_PERM.CUID or SHM_PERM.UID. Return Value: Return 0 if the call is successful, otherwise return -1. In this example, this example includes all shared memory operating system calls: #include #include #include #define shmkey 74 #define k 1024 int shmid; cleanup () {shmctl (shmid, ipc_rmid, 0); exit (0) .} main () {Int * Pint;
Char * addr1, * addr2; extern char * shmat (); extern cleanup (); for (i = 0; i <20; i ) Signal (i, cleanup); shmid = shmget (shmKey, 128 * k, 0777 | IPC_creat); addr1 = shmat (SHMID, 0, 0); addr2 = shmat (shmid, 0, 0); Printf ("ADDR1 0x% x addr2 0x% x / n", addr1, addr2); PINT = (int * Addr1; for (i = 0; i <256; i ) * PINT = i; PINT = (int *) addr1; * pint = 256; PINT = (int *) addr2; for (i = 0; i <256 ; i ) Printf ("index% D / TVALUE% D / N", I, * PINT ); SHMDT (addr1); shmdt (addr2); pause ();} 21. SemctL () function: Signal control operation. Syntax: #include #include #include int Semctl (SemID, Memnum, Cmd, Arg) int SemID, Semnum, Cmd; union semun {int val; struct semid_ds * buf; ushort * array;} arg; Description: This system call is provided A semaphore control operation, the operational behavior is defined by the CMD, which is operated on the amount of semaphum specified by SemID and semnum. Each command requires a corresponding permission level:. GetVal: Returns the value of Semval, requirement Read rights. SetVal: Set the value of the semval to arg.val. After this command is successfully executed, all the semadj's values corresponding to all the semaphones are cleared, and the modification permissions are required.. GetPid: Return the value of SEMPID, requirement Have read permissions. Return the value of the semncnt, require read privileges.. Getzcnt: Returns the value of the semzcnt, requires read privileges. The following command operates on a set of semapas:. GetAll: Return each The value of SEMVAL, simultaneously puts each value into the array pointed to by arg.Array. When this command is successfully executed, the signal amount of all the processes corresponding to the semadj is cleared, and the modification permission is required.. SE Tall: Sets each SEMVAL value based on Arg.Array. After this command is successfully executed, the semadj's value of all processes corresponding to all processes are cleared, and there is a modification. The following command is valid in any case. :. IPC_STAT: Put the value of each member of the data structure related to the SEMID into the structure points to the arg.buf. Requires read privileges.. IPC_set: Set the following members of the SEMID related data structure, set data from Arg. Read in the structure points to the BUF: SEM_PERM.UID SEM_PERM.GID SEM_PERM.MODE This command can only be operated by a valid UID equal to the process or effective UID of SEM_PERM.CUID or SEM_PERM.UID.. IPC_rmid: Delete by SemID The specified semaphore size identifier and related set of semaphones. This command can only be operated by a valid UID equal to the process or effective UID of SEM_PERM.CUID or SEM_PERM.UID. Return Value: If you call success The value of the following values are returned according to CMD: getVal: semval value. GetPID: SemPid value. GetNCNT: Semncnt value. Getzcnt: semzcnt value. Other: 0. Return -1. 22.Semget () function : Get a set of semaphors. Syntax: #include #include #include int semget (key, nsems, semflg) key_t key; int NSEMS, SEMFLG;
Description: Returns the signal quantifier associated with the key. If the facts are true, then the signal size identifier, the associated SEMID_DS data structure and a set of NSEMS seminars will be created:. KEY is equal to IPC_Private.. There is no signal to Key, and the Semflg & IPC_CREAT is true. The SEMID_DS data structure related to the new semaphore is initialized as follows:. In the operation permission structure, SEM_PERM.CUID and SEM_PERM.UID set equal to the valid UID of the calling process In the operation permission structure, SEM_PERM.CGID and SEM_PERM.GID settings are equal to the valid GID of the calling process.. Access permission bit SEM_PERM.MODE setting is equal to the access ratio of Semflg. SEM_ITIME setting equal to 0, SEM_CTIME setting equal to the current system Time. Return Value: If the call is successful, return a non-zero identifier, referred to as a signal amount identifier; otherwise returns -1. 23.Semop () function: Signal operation. Syntax: #include #include #include int SMOP SEMID, SOPS, NSOPS) INT SEMID; STRUCT SEMBUF * SOPS; Unsigned NSOPS; Description: This system calls the behavior collection for performing user-defined operations on a set of semaphors. The quantity is related to SEMID. Parameter SOPS is A user-defined semaphore. An array pointer. Parameter NSOPS is the number of elements of the array. Each element structure of the array includes the following members: SEM_NUM; / * Signal number * / SEM_OP; / * Signal operation * / SEM_FLG ; / * Operational flag * / Each semaphore operation in this system call definition is for the amount of signal specified by SEMID and SEM_NUM. Variable SEM_OP Specifies one of three semaphores:. If SEM_OP is a negative number and calling process With modification, one of the following conditions will happen: * If SEMVAL is not less than the absolute value of SEM_OP, the absolute value of SEM_OP is subtracted to the value of SemVal. If (SEMFLG & SM_UNDO) is true, the absolute value of SEM_OP is added to the call process. The Semadj value of the specified semaphore. * If SEMVAL is less than the absolute value of SEM_OP, this call is immediately returned. * If SEMVAL is less than the absolute value of SEM_OP, the system call will Increase the SemNCNT value (plus one) of the specified semaphore (plus) to hang up the calling process until one of the following conditions is satisfied: (1). Semval value becomes an absolute value of not less than SEM_OP. When this occurs, specified Sems-related Semncnt minus one, if (SEMFLG & SEM_UNDO) is true, the absolute value of SEM_OP is added to specify the semadj value of the signal amount. (2). The calling process waitsible SEMID has been deleted by the system. (3). Call process Troud to the signal, at this time, the SEMNCNT value of the specified semap is reduced. The process executes the interrupt service program. If the SEM_OP is a positive value, the call process has a modification permission, and the value of SEM_OP plus the value of SEMVAL, if ( Semflg & Sem_undo) is true, then SEM_OP subtracts the semadj value of the calling process to specify the semaphore. If the SEM_OP is 0, the calling process has read rights, one of the following cases will happen: * If SEMVAL is 0, the system call immediately returns immediately * If SEMVAL is not equal to 0 and (SEMFLG & IPC_NOWAIT) is true, the system calls return immediately. * If SEMVAL is not equal to 0 and (SEMFLG &
IPC_nowait is false, this system call will add the Semzcnt value of the specified semaphore, hang up the call process until one of the following cases occur: (1). Semval value is 0, the SemzcNT value of the specified semaph is reduced. (2). The SEMID waiting for the process has been deleted by the system. (3). Calling process sways to the signal, at this time, the SEMNCNT value of the specified semaphore is reduced, the process performs the interrupt service program. Return Value: call success: call success Then return 0, otherwise returns -1. Example: This example will call all system calls included in the above-described semaphore: #include #include #include #define semkey 75 int SemId; unsigned int count; / * in file sys / sem.h SEMBUF structure * Struct sembuf {* unsigned short sem_num; * short sem_op; * short sem_flg; *} * / struct sembuf psembuf, vsembuf; / * p and v operation * / cleanup () {SemctL (SEMID, 2, IPC_rmid, 0); exit (0);} main (argc, argv) int Argc; char * argv []; {INT I, FIRST, SECOND; Short InitArray [2], OutArray [2]; extern cleanup (); IF (argc == 1) {for (i = 0; i <20; i ) signal (i, clearup); SEMID = SEMGET (SemKey, 2,0777 | ipc_creat); IPC_CREAT); IPCRAY [0] = ITARRAY [1] = 1; SemcTl (SEMID, 2, SETALL, INITARRAY); SemCTL (SemID, 2, Getall, OutArray); Printf ("SEM INIT VALS% D% D / N", OutArray [0], OutArray [1]); PAUSE (); / * Sleep to be woken up by a software interrupt * /} else if (argv [1] [0] == 'a') {first = 0; second = 1;} else {first = 1; second = 0;} Semid = Semget (SemKey, 2,0777); psembuf.sem_op = -1; psembuf.sem_flg = SEM_UNDO; vsembuf.sem_op = 1; vsembuf.sem_flg = SEM_UNDO; for (count = 0 ;; xcount ) {psembuf.sem_num = first; semop (semid, & psembuf, 1); psembuf.sem_num = second; semop (SemID, & Psembuf, 1); Printf ("Proc% D count% d / n", getpid (), count); vsembuf.Sem_num = second; Semop (SemID, & Vsembuf, 1); vsembuf.sem_num = first; SEMOP (SEMID, & VSEMBUF, 1);}} 24.sdener () function: Share data segment synchronous access, lock. Syntax: #include int Sder (Addr, flags) char * addr; int flags;
Description: Used to indicate that the calling process will access the content in the shared data segment. The parameter addr is a valid return code that calls an SDGET () call. The action executed depends on the value of the Flags:. SD_NOWAIT: If another process is already The specified segment calls the system call and has not called Sdleave (), and the segment is not created with the SD_UNLOCK flag, then the calling process is not waiting for the paragraph idle but immediately returns an error code. SD_WRITE: Indicates the calling process to share data segments Write data. At this point, another process is coupled to the shared data segment without being allowed. Return Value: Return 0, otherwise return -1. 25.sdleave () function: shared data segment Sync Access, unlock Syntax: #include int SdleVe (AddR, Flags) Char * Addr; Description: Used to indicate that the calling process has completed the content in the shared data segment. Return value: Return 0, otherwise returns -1. 26.sdget () Function: Connect shared data segment into the data space of the calling process. Syntax: #include char * sdget (path, flags, size.mode) char * path; int flags; long size; int mode; Description: This system call In the data segment of the calling process, the shared data segment is connected to the data segment of the calling process, the specific action is defined by the value of the FLAGS: SD_RDONLY: The join segment is read-only. SD_WRITE: The join paragraph is readable and writable.. Sd_creat: If it is made by Path The named segment exists and not in use, the role of this flag is the same as the same segment, otherwise, this segment is created according to the value process of Size and Mode. The read and write access to the segment is awarded by MODE, function and The general file is the same. Segment is initialized to all 0.. SD_UNLOCK: If you create this paragraph, use this flag, allow multiple processes to be accessed (in reading and writing). Return Value: Return to join Segment address. Otherwise, returning -1. 27.sdfree () function: Interrupt the shared data segment from the data space of the calling process. Syntax: #include int SDFree (AddR) char * addr; Description: This system call will share Data segments are separated from the specified address of the data segment of the calling process. If the call is called, SDLEAVE () is not called, and Sdleave () is called automatically, and then this call is sent. Work. Return Value: Returns the join segment address if the call is successful. Otherwise, returns -1. 28.sdgetv () Function: Synchronize Share Data Access. Syntax: #include int SDGetv (AddR) char * addr; Description: Used to synchronize coordination is using the process of shared data segments. Return to the version number of the shared data segment. When there is a process pair When this paragraph is a Sdleave (), the version number will be modified. Return Value: If the call is successful, return to the version number of the specified shared data segment, otherwise return -1. 29.sdwaitv () function: Synchronize Share Data Access. Syntax : #include int SDWAITV (AddR, vnum) Char * Addr; int vnum; Description: Used to synchronize coordination is using the process of shared data segment. Return the value of the version number of the shared data segment. Calling process will sleep until the version of the specified segment No longer equal to VNUM; return value: If the call is successful, return to the version number of the shared data segment, otherwise return -1. 30.sbrk () function: Modify the data segment space allocation. Syntax: char * sbrk (incr) INT InCr; Description: Used to dynamically modify the spatial assignment of the calling process data segment. Process will reset the segmentation value of the process and assign a space for a suitable size. The segmentation value is the first assigned address outside the data segment. To assign The amount of space is equal to the amount of segment value. The newly allocated space is set to 0. If the same memory space is reassigned to the same process, the content of the space is uncertain. Return value: If successful call, return value is 0 Otherwise, returning -1. Example: This example will include all system calls including the shared data space operation: char * area1; char buf [21]; intv; / * acquire or create a shared data space (system special file), Name is / TMP / Area1, the length is 640, user access is 0777 * / area1 = SDGET ("/ tmp / area1", sd_write | sd_creat, 640, 0777); if ((int) area1 =
= -1) {Printf ("Get Share Data Segment Area1 Failed / N"); EXIT (1);} / * Acquisition of the version number * / v = sdgetv (Area1) of the shared data segment Area1; / * Apply Access Sharing Data Section Area1, if the process is accessed, the process is sent, otherwise, enter the access and write the data segment * / sdenter (area1, sd_write); / * Access to the shared data segment, write 10 A * / STRCPY (Area1, "Aaaaaaaaaaaa"); / * Apply to unpack access, activate the process * / SdleAVE (Area1) if the process application access; / * Process processing * / / * Wait to take the shared data section Area1 The version number * / sdwaitv (area1, v); / * Re-apply access shared data segment area1 * / sdenter (area1, sd_write); / * read the data in the shared data * / Memcpy (buf, Area1, 20) ; / * Apply for access to access, activate the process * / sdleave (Area1) if there is a process application access; Printf ("THE DATA NOW IN AREA1 IS [% S] / N", BUF); 31.Getenv () Function: Get the specified environment variable. Syntax: #include #include char * getENV (Name) Char * name; Description: This system calls check environment strings (formats such as name = value) and find the name of the name After returning a pointer to the Value string. Otherwise, return a null pointer: Return value: as a foregoing. Example: char * value; value = getenv ("home"); printf ("Home = [% s] / n", VALUE ); / * Will print the value of the Home environment variable * / 32.putenv () function: Modify or add ambient value. Syntax: #include int putenv (String) char * string; Description: Parameters string point to a string, format As follows: name = value This system calls Environment variable Name equal to value value value value value value, modify, or adds an environment variable, string String a part of the environment. Return Value: If Putenv () cannot get the right memory space, return non-0 value, Otherwise, Returns: / * Parent Processing * / Putenv ("HOME = / Home / Abcdef"); Putenv ( "Path = / bin"); if (fork ()> 0) exit (0); / * Parent process exits the running * / / * child process processing * / setpgrp (); / * The environment variable set by the parent has passed Go to the sub-process * / char * value1; value1 = getenv ("home"); value2 = getenv ("path"); printf ("Home = [% s], path = [% s] / n", value1, value2 ); / * Will print "home = / home / abcdef" and "pat = / bin"
* / 3. Multi-process programming skills 1. Main program structure (1) Event master mode If the application belongs to the transaction method, the main function is designed as a monitoring event. When the event occurs, a new process can be generated. To process the transaction, the child process exits the system after the transaction is complete. This processing method generally does not want messaging. (2) If the information coordination method is required to be completed by multiple processes, you can generate these processes. By passing the message between the processes, each process can coordinate and complete the transaction together. This processing method is generally after generating several processes, using EXEC () to call other program files, so that different programs are simultaneously The system is running in the system. Then via the IPC mechanism, allow each program to be coordinated. 2. Select the main bifurcation point (1) Event initial generation program structure corresponding to the event master mode. Key point to select events The initial occurrence point, such as the chain information given by the web program. The master program is considered to be an event after receiving the message, then a child process is generated: Receive transaction information, transaction processing, send Returns the transaction information, shutting down the link, etc. After completing the sub-process exits the system. (2) The main program is independently generated in the program structure of the information coordination mode. The master program is only responsible for generating several child processes, each sub-process calls EXEC () Turn different execution files into memory operation, the master program can exit the system after generating all child processes, and leave the child process in memory. 3. Process relationship processing (1) Parental process relationship. Process group processing The concept of the process group is this. When the system starts, the first process is init, the process group number is equal to the process number, and the process group number of all the sub-process it produces is the same, the child process of the sub-process also inherits Process group number, this, all sub-process generated by init belongs to the same process group. However, the parent-child process of the same process group may communicate with each other on the signal, if the parent process quits the system, then The process will become an orphan process that may become a zombie process. Thus, the child is not "willing"
Under the case of exiting the run. To solve this problem, the child process can make itself a new process group, that is, call setPgrp () and the original process group to leave the relationship, generate a new process group, the process group number is the same as its process number In this way, the parent process does not affect the current operation of the child process after exiting the run. The child process signal is handled, but the above process cannot solve another difficulty, that is, the child process does not find his parent process. (The parent process has exited, the parent process number of the child process is changed to 1). If the sending child process exits the signal, there is no response process that does not have a parent process. The child process cannot completely exit operation, which may enter a zombie state. So the parent process is Preferably, the child process returns the processing of the sub-process, generates a child process, after the parent process exits, the child process returns the process of returning the signal, and the system is given by the system, and the child process can be properly exited. (2) Brother process relationship. Exchange process number For information on information coordination, each brother process needs to know each other to understand the process number to facilitate signal processing mechanism. The relatively reasonable method is that the parent process generates a shared memory space Each child process sets its own process number in the shared memory at startup. This way, when a child process sends a signal to another or because other reasons need to know another child process number, you can share Access to memory get the required process number. 4. Inter-process communication processing (1) Shared memory requires lock mechanisms Due to the design of the lock, there is no processing lock mechanism during the shared, and there are multiple processes to have problems when accessing the shared memory. For example, a process modifies a shared memory unit, and another process may have a third process to immediately modify the unit immediately, which will affect the correctness of the program. At the same time, there is also a division system for each process. The time sheet processing may cause different correctness. According to the operation mode of the operating system, there is a read lock and write lock to ensure the consistency of the data. So the shared memory without the lock mechanism must be used with the signal. In order to ensure the correct operation of shared memory. (2) Message Queue Requires Key Value Message Queuing Operation After accessing the message queue, you must read the same key value in the message queue, write a message. Enter the message key. This can distinguish between different transactions through different key values, so that the same message queue can be used simultaneously without conflict. If the reading message queue uses the key value 0, read the first queue in the message queue. Message, regardless of its key value. (3) Signals require signal processing function settings and reset When the user process needs to do handles yourself, you can define the interrupt processing function yourself, and set the interrupt processing function and the Interrupts are associated. In this way, after receiving the interrupt, the user-defined function is called, and the user process will continue to run from the interruption after the processing is completed. The interrupt function defined by the user does not have a long hop function or an exit operation, which changes the running command address. After the interrupt signal is processed, the interrupt process is restored to the last default processing function instead of maintaining a user-defined function. Therefore, in the user-defined interrupt processing function, it is generally defined to define the interrupt and function's own association. (4) IPC's permissions set in the message queue, shared memory, and semaphore, there is user access settings, class The settings of the file access, such as (777), use the command IPCS to see the message queue generated in the system, shared memory and semaphore access rights. The meaning is similar to file access. Just the execution bits are invalid The user's access rights are defined in the system file in the famous pipe and file mode sharing memory. Use the command ls -l to see that they exist and have access to the system file, and can see the file with a famous pipeline. The type of file type P, file mode sharing memory is S. (5) Signal Interrupt The Interrupt Problem is considering the interrupt processing problem when the system calls level valid system in the design system. When the process is running to a system call, it has been interrupted. The process enters the interrupt process. After the processing is complete, the process will skip the system call to enter the next program instruction. It should be noted that the interrupt occurs at the system call level instead of the subroutine or function level. For example, a program is A subroutine is set to the timeout interrupt before being called, and the timeout interrupt is received in the subroutine, and the system will then process the subroutine after the interrupt system call after processing, instead of call the subroutine name. The latter instructions continue to process. (6) Features of various IPC methods. Message queue: