小白笔记----------fork.c

来源:互联网 发布:淘宝口令在哪里找到 编辑:程序博客网 时间:2024/05/21 11:26
Mark一下fork的用法。。。。
/******************************************************* Author       : Aaron92* Date   : 2016-04-29 15:53* Filename     : fork.c* Description  : ******************************************************/#include<stdio.h>#include<stdlib.h>#include<sys/types.h>#include<unistd.h>#define oops(s,x) { perror(s);exit(x);}/*error method*/#define MAXDELAY10main(int argc, char ** argv){void child_code(int),parent_code(int);pid_t pid;int i,n,delay;if( argc == 1){fprintf(stderr,"usage:sol08.8b number of children\n");exit(1);}n = atoi(argv[1]);srand(getpid());/*get the seed for the random function*/printf("before:mypid is %d\n",getpid());for(i = 0; i < n;i++){delay = 1 + (rand()% MAXDELAY);pid = fork();if(pid == -1){oops("fork",2);}if(pid == 0){child_code(delay);}}parent_code(n);}void child_code(int delay){printf("child %d here will sleep for %d seconds\n",getpid(),delay);sleep(delay);printf("child done about to exit\n");exit(17);}void parent_code(int n){int wait_rv;printf("waiting for %d children\n",n);while((wait_rv = wait(NULL)) != -1){printf("wait returned : %d ,%d to go\n",wait_rv,--n);}}

0 0
原创粉丝点击