1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| /************************************************************************* > File Name: fork0.c > Author:perrynzhou > Mail:perrynzhou@gmail.com > Created Time: Sun 16 Jun 2019 01:55:54 PM CST ************************************************************************/
#include <stdio.h> #include <getopt.h> #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int is_num(const char *s) { if (NULL == s) { return -1; } size_t len = strlen(s); for (int i = 0; i < len; i++) { if (isdigit(s[i]) == 0) { return -1; } } return 0; } int main(int argc,char *argv[]) { int pn, fn; int default_pn = 2; const char *cmd_line = "p:"; char ch; while ((ch = getopt(argc, argv, cmd_line)) != -1) { int flag = is_num(optarg); switch(ch) { case 'p': pn = (flag == 0) ? atoi(optarg) : default_pn; break; default: break; } } fprintf(stdout,"process number:%d\n",pn); fflush(NULL); for (int i = 0; i < pn; i++) { fflush(NULL); pid_t pid = fork(); if (pid == -1) { perror("fork()"); exit(1); } if (pid == 0) { fprintf(stdout, "child process %ld,parent process %ld\n", getpid(), getppid()); //sleep(100000); exit(0); } } sleep(10000); exit(0); return 0; }
|