fork - 利用信號在父子進程間傳遞指針的實驗


接上篇文章,父子進程間可以傳遞數據,那么能傳遞指針嗎?我們來試試:

 
1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<unistd.h>
  4 #include<stdlib.h>
  5 #include<signal.h>
  6 #include <sys/types.h>
  7 #include <sys/wait.h>
  8 void handler_sigint(int signo,siginfo_t *siginfo,void*pvoid)
  9 {
 10         int *a;
 11         a=(int*)(siginfo->si_ptr);
 12         printf("recv SIGINT,the pointer data is %d\n",*a);
 13 }
 14 int main(int argc,char*argv[])
 15 {
 16         pid_t pid;
 17         switch(pid=fork())
 18         {
 19                 case -1:
 20                         printf("fork error\n");
 21                         break;
 22                 case 0:
 23                 {
 24                         printf("child process is running\n");
 25                         struct sigaction act;
 26                         act.sa_sigaction=handler_sigint;
 27                         act.sa_flags=SA_SIGINFO;
 28                         sigaction(SIGINT,&act,NULL);
 29                         pause();
 30                         break;
 31                 }
 32                 default:
 33                 {       union sigval value;
 34                         int signum=SIGINT;
 35                         int i,stat;
 36                         value.sival_ptr=&signum;
 37                         printf("parent process is running\n");
 38                         int *a;
 39                         a=(int *)value.sival_ptr;
 40                         printf("In the father process,the pointer data is %d\n",*a);
 41                         if(argc!=1&&argc!=3&&argc!=5)
 42                         {
 43                                 printf("./send_pointer\n");
 44                                 exit(1);
 45                         }
 46                         for(i=1;i<argc;i++)
 47                         {
 48                                 if(!strcmp(argv[i],"-s"))
 49                                 {
 50                                         signum=atoi(argv[i+1]);
 51                                         continue;
 52                                 }
 53                         }
 54                         sleep(5);
 55                         if(sigqueue(pid,signum,value) < 0)
 56                         {
 57                                 perror("sigqueue");
 58                                 exit(1);
 59                         }
 60                         wait(&stat);
 61                         break;
 62                 }
 63         }
 64         return 0;
 65 }



運行結果:
[wjl@wjl-desktop ~/c/signal 17:58:37 #86]$ ./send_pointer
parent process is running
In the father process,the pointer data is 2
child process is running
recv SIGINT,the pointer data is 9199808



從結果可以看到指針可以傳遞過去,但是指針所指的值變化了,為什么呢?答案很簡單,在進程那部分,我們一直在強調一點:父子進程的地址空間是相互獨立的!所以在父子進程間傳遞指針是沒有意義的。

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com