1.需要循环创建50个进程作为某种客户端连接服务器进行操作,由于fork理解不够深,如下操作 #include<stdlib.h> #include<string.h> #include <unistd.h> #include <stdio.h>

int num1 = 0; int num2 = 0; int add(int pid) { int i = 0; for(i=0; i<10; i++) { printf("My Process id is=%d, sum=%d\n", pid, num1+num2); num1++; num2++; sleep(2); } printf("the process over id=%d\n", pid); return 0; }

int main() { pid_t fpid; int count =0; int i = 0; printf("input the fork count:\n"); scanf("%d", &count); for(i=0; i< count; i++) {

  if(fpid< 0)
  {
  	 printf("fork error\n");
  	 exit(-1);
  }else if(fpid == 0)
  {
  	 printf("I am the child process, my Process id is=%d, fpid=%d\n", getpid(), fpid);
  	 add(getpid());
  }else 
  {
  	printf("I am the parent process, my process id is=%d, fpid=%d\n", getpid(),fpid);
  }

}

return 0; } 输入50后,产生了无数进程,总之没有计算赶紧将电脑重新启动了。

2.fork创建进程

子进程是父进程的复制品。例如,子进程获得 父进程数据空间、堆和栈的复制品。注意,这是子进程所拥有的拷贝。父、子进程并不共享这 些存储空间部分。如果正文段是只读的,则父、子进程共享正文段。 f o r k有两种用法: (1) 一个父进程希望复制自己,使父、子进程同时执行不同的代码段。这在网络服务进程 中是常见的——父进程等待委托者的服务请求。当这种请求到达时,父进程调用 f o r k,使子进 程处理此请求。父进程则继续等待下一个服务请求。 (2) 一个进程要执行一个不同的程序。这对 s h e l l是常见的情况。在这种情况下,子进程在 从f o r k返回后立即调用e x e c

waitpid用法参考https://blog.csdn.net/u011068702/article/details/54409273

正确创建50个进程

#include<stdlib.h> #include<string.h> #include <unistd.h> #include <stdio.h>

int num1 = 0; int num2 = 0; int g_pid[50] = {0}; int g_num = 0; int add(int pid) { int i = 0; for(i=0; i<10; i++) { printf("My Process id is=%d, sum=%d\n", pid, num1+num2); num1++; num2++; sleep(2); } printf("the process over id=%d\n", pid); return 0; }

int worker(int i) { int pid = fork(); switch(pid) { case 0: g_pid[i] = pid; printf("I am the child process, my Process id is=%d, fpid=%d\n", getpid(), pid); add(getpid()); exit(0);; case -1: printf("[Worker]: Fork failed!\n"); exit(0); default: break; } }

int main() { pid_t fpid; int count =0; int i = 0; printf("input the fork count:\n"); scanf("%d", &count); g_num = count; for(i=0; i< count; i++) {

worker(i);

/* fpid = fork(); if(fpid< 0) { printf("fork error\n"); exit(-1); }else if(fpid > 0) { printf(" I am the parent process, my process id is=%d, fpid=%d\n", getpid(),fpid); continue; }else { printf("I am the child process, my Process id is=%d, fpid=%d\n", getpid(), fpid); add(getpid()); }/ / if(fpid< 0) { printf("fork error\n"); exit(-1); }else if(fpid == 0) { printf("I am the child process, my Process id is=%d, fpid=%d\n", getpid(), fpid); add(getpid()); }else { printf("I am the parent process, my process id is=%d, fpid=%d\n", getpid(),fpid); }*/ }

for(i=0; i<g_num; i++) { waitpid(g_pid[i],NULL, 0); printf("wait the sun process\n"); } printf("father process over\n"); return 0; }