Linux fork的頭次使用

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章