Chinaunix首页 | 论坛 | 博客
  • 博客访问: 371251
  • 博文数量: 47
  • 博客积分: 967
  • 博客等级: 准尉
  • 技术积分: 1290
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-25 16:14
文章分类

全部博文(47)

文章存档

2019年(1)

2014年(1)

2013年(9)

2012年(36)

分类: LINUX

2012-07-13 17:00:24

题目是这样的:一个进程产生三个子进程,并传递不同的参数,让他们分别执行别的程序:

解释如下:一个父进程产生三个子进程,可以有很多方法,但是必须要保证是同一父进程。具体代码如下:

test22.c

  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5.                     
  6. int main(int argc,char * argv[],char ** environ)
  7. {
  8.     int i;
  9.     pid_t pid1,pid2,pid3;
  10.     int stat_val;
  11.     for(i=1;i<4;i++)
  12.     {
  13.      if(strcmp("a",argv[i])==0)
  14.      {
  15.       pid1=fork();
  16.         if(pid1==0)
  17.         {
  18.         printf("My pid = %d ,parentpid = %d\n",getpid(),getppid());
  19.         execve("cheng",argv,environ);// 让进程去执行新的程序。
  20.         return 0;
  21.         }
  22.      }
  23.      if(strcmp("b",argv[i])==0)
  24.      {
  25.       pid2=fork();
  26.         if(pid2==0)
  27.         {
  28.         printf("My pid = %d ,parentpid = %d\n",getpid(),getppid());
  29.         execve("jiecheng",argv,environ);
  30.         return 0;
  31.         }
  32.      }
  33.     if(strcmp("c",argv[i])==0)
  34.      {
  35.       pid3=fork();
  36.         if(pid3==0)
  37.         {
  38.         printf("My pid = %d ,parentpid = %d\n",getpid(),getppid());
  39.         execve("kou",argv,environ);
  40.         return 0;
  41.         }
  42.      }
  43.     }
  44.     for(i=0;i<10000000;i++);
  45.     wait(&stat_val);
  46.     return 0;
  47. }
cheng.c的源码如下:

cheng.c

  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4.              
  5. int main(int argc,char *argv[],char **environ)//注意参数
  6. {
  7.   printf("123\n");
  8.               
  9. }

jiecheng.c和kou.c类似。

编译过程如下:

点击(此处)折叠或打开

  1. lwp@lwp-linux:~/linux/bianchengshizhan/_7_$ gcc -o cheng cheng.c
  2. lwp@lwp-linux:~/linux/bianchengshizhan/_7_$ gcc -o jiecheng jiecheng.c
  3. lwp@lwp-linux:~/linux/bianchengshizhan/_7_$ gcc -o kou kou.c
  4. lwp@lwp-linux:~/linux/bianchengshizhan/_7_$ gcc -o test22 test22.c
  5. lwp@lwp-linux:~/linux/bianchengshizhan/_7_$ ./test22 a b c
  6. My pid = 3114 ,parentpid = 3113
  7. My pid = 3115 ,parentpid = 3113
  8. My pid = 3116 ,parentpid = 3113
  9. liwenping
  10. 123
  11. 98

阅读(3130) | 评论(1) | 转发(3) |
给主人留下些什么吧!~~

yuapple5552014-09-18 12:44:33

转了,留着学习学习