c++-多进程

 

深未来技术原创文章,如转载,请注明来源http://deepfuture.iteye.com/blog/748242!

test为产生子进程的父进程,x为子进程,注意x非test进程复制品,因为非fork创建

执行结果为:

deepfuture@deepfuture-laptop:~$ ./test

子进程ID为7376

子进程ID为7377

66

url为deepfuture.iteye.com

66

deepfuture调用了我

(null)子进程ID-->进程状态=====>7376-->0

55

url为deepfuture.iteye.com

55

deepfuture调用了我

(null)子进程ID-->进程状态=====>7377-->0

url为(null)

 

 

 

test.c源代码:

 

#include <spawn.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/wait.h>

 

 

int main(){

   int stat;//wait取得进程执行状态

   posix_spawnattr_t Attr;

   posix_spawn_file_actions_t FileActions;

   pid_t Pid;

 

   char *const myargv[]={"/home/deepfuture","deepfuture",NULL};//要调用程序的路径/home/deepfuture和调用这个程序的参数deepfuture,NULL结尾

   char *const myargp[]={"myurl=deepfuture.iteye.com",NULL};//环境列表,NULL结尾

   posix_spawnattr_init(&Attr);//用默认值初始化新进程的调度、进程 组、信号及标记信息 

   posix_spawn_file_actions_init(&FileActions); //用默认值初始化文件描述符  

 

   posix_spawn(&Pid,"x",&FileActions,&Attr,myargv,myargp);//进程

   printf("子进程ID为%d\n",Pid);//子进程PID

   posix_spawn(&Pid,"x",&FileActions,&Attr,myargv,myargp);//进程

   printf("子进程ID为%d\n",Pid);//子进程PID

   Pid=wait(&stat);//异步进程调用,通过wait挂起,并将进程状态返回到stat中

   printf("子进程ID-->进程状态=====>%d-->%d\n",Pid,stat);//子进程PID-->进程状态

   Pid=wait(&stat);//异步进程调用,通过wait挂起,并将进程状态返回到stat中

   printf("子进程ID-->进程状态=====>%d-->%d\n",Pid,stat);//子进程PID-->进程状态

   unsetenv("myurl");//清除环境变量

   return(0);

}

深未来技术原创文章,如转载,请注明来源http://deepfuture.iteye.com/blog/748242!

 

x.c源代码:

#include <stdio.h>

#include <stdlib.h>

int main(int argc,char *argv[]){

  int x;

  scanf("%d",&x); //接受键盘输入 

  printf("url为%s\n%d\n%s调用了我\n",getenv("myurl"),x,argv[1]);//getenv("myurl")取得环境变量

  return (0);

}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值