设为首页 加入收藏

TOP

进程通信中如何进行值的传递?(一)
2017-06-20 10:22:53 】 浏览:391
Tags:进程 通信 如何 进行 传递

子进程中修改了程序的某个全局变量的值,如何在其他子进程中或者父进程中取得修改后的值,除了连数据库之外,还可以通过共享内存来获取。


举例说明:


#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;                                  //记录fork()的返回值,用于区别父子进程
  char *Message;                              //用于记录输出信息
  int LoopVal;      //用于记录父子进程的循环次数
  int LoopVal1;      //用于循环
  int ExitCode;
  int P1 = 100; //定义一个全局变量的初值。后面子进程中修改这个变量的值。
  printf("the new fork starting\n");
  pid=fork();                                        //新建子进程
  switch(pid)
    {
    case -1:      //建立进程错误     
    printf("creat new fork error!");
    exit(1);
    case 0:                                          //子进程
      Message = "This is in the child process";
      printf("childid=%d\n",getpid());
      LoopVal = 7;
      ExitCode = 24;
      key_t  key = ftok(".",100);
    if(key ==-1)
  {
      printf("出错了\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 ;//子进程中对全局变量进行加1操作。父进程后续去取这个修改后的值。
  shmdt(p);
  exit(0);
    default:                                        //父进程
      Message = "This is in the parent process,waiting the child finished........\n";
      printf("pareentid=%d\n",getpid());
      LoopVal = 5;
      ExitCode = 15;
      key_t key1 = ftok(".",100); //父进程指向子进程共享的那块内存。
    int shmid1 = shmget(key1,0,0);
    printf("shmid = %d\n",shmid1);
    void *p1 = shmat(shmid1, 0, 0);//获取到子进程中修改后的全局变量的地址。
    int *pi1 = p1;
    printf("*pi1=%d\n",*pi1);//打印子进程中修改后的值。
    shmdt(p1);
      break;
    }
    printf("LoopVal=%d\n",LoopVal);
  for(LoopVal1=0;LoopVal1<LoopVal;LoopVal1++)
    {
      puts(Message);
      sleep(1);
    }
 
  if(pid!=0)        //父进程
    { 
   
      int Stateva l;
     
      pid_t ChildPid;
      ChildPid = wait(&Stateva l);        //用Stateva l记录状态信息
      //
      printf("The child has finished with  the PID of %d\n",ChildPid);
      if(WIFE

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java中抽象类的定义和使用 下一篇Go语言生成uuid

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目