A child process modifies the value of one of the program's global variables, how to get the modified value in other child processes or in the parent process, and can be obtained through shared memory in addition to the database.
To illustrate:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
int main ()
{
pid_t pid; Record the return value of fork () to distinguish the parent-child process
Char *message; Used to record output information
int loopval; Number of cycles used to record parent-child processes
int LoopVal1; For loop
int ExitCode;
int P1 = 100; Defines the initial value of a global variable. The value of this variable is modified in the post-face process.
printf ("The New Fork starting\n");
Pid=fork (); New Child process
Switch (PID)
{
Case-1://Build Process Error
printf ("Creat new fork error!");
Exit (1);
Case 0://child process
Message = "This was in the child process";
printf ("childid=%d\n", Getpid ());
Loopval = 7;
ExitCode = 24;
key_t key = Ftok (".", 100);
if (key ==-1)
{
printf ("Error \ n");
return-1;
}
int id = shmget (key,4,ipc_creat| ipc_excl|0666);
printf ("id =%d\n", id);
void *p = Shmat (id,0,0);
int *pi = p;
*PI = p1+1;//The global variable is added to the 1 operation in the sub-process. The parent process subsequently takes the modified value.
SHMDT (P);
Exit (0);
Default://Parent process
Message = "This was in the parent process,waiting the child finished........\n";
printf ("pareentid=%d\n", Getpid ());
Loopval = 5;
ExitCode = 15;
key_t Key1 = Ftok (".", 100); The parent process points to the memory that the child process shares.
int shmid1 = Shmget (key1,0,0);
printf ("Shmid =%d\n", SHMID1);
void *p1 = Shmat (shmid1, 0, 0);//Gets the address of the modified global variable to the child process.
int *pi1 = P1;
printf ("*pi1=%d\n", *pi1);//Print the modified value in the child process.
SHMDT (p1);
Break
}
printf ("loopval=%d\n", loopval);
for (loopval1=0; loopval1<loopval; loopval1++)
{
Puts (Message);
Sleep (1);
}
if (pid!=0)//Parent process
{
int stateval;
pid_t Childpid;
Childpid = Wait (&stateval); Record status information with Stateval
//
printf ("The child had finished with the PID of%d\n", childpid);
if (wifexited (stateval))//If the child process ends normally, it takes a non-0 value
{//Description: Wexitstatus just as opposed to wifexited, when the child process ends normally, it takes a value of 0, an abnormal end, and a non-0 value.
printf ("The child processxx have exit with code%d\n", Wexitstatus (Stateval));
}//If wifexited nonzero, it returns the exit code of the child process
Else
printf ("The child has terminated abnormally\n");
}
printf ("end--"); Child process Abnormal End
Exit (ExitCode);
}
How is it worthwhile to deliver in process communication?