建立子程序的4種方法及注意事項
阿新 • • 發佈:2019-02-11
/***********************************fork & vfork*********************************/1
1. fork:子程序拷貝父程序的資料段
vfork: 子程序與父程序共享資料段
2. fork: 父、子程序的執行順序是隨機的
vfork: 先執行子程序,後執行父程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("fork = %d\n",getpid());
if(argc != 3)
{
printf("Please input two param!\n");
exit(1);
}
int i;
for(i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n",i,argv[i]);
}
pid_t pid;
/*此時僅有一個程序,*/
int count = 0;
pid = fork();
/*此時已經有兩個程序在運行了*/
if(pid < 0)
{
perror("fork error!");
exit(1);
}
if(pid == 0)
{
count++;
printf("child count = %d\n",count);
sleep(5);
exit(1); // 使用vfork建立子程序時,必須要使用exit(1)來異常退出子程序,這樣才能使得父、子程序共享的資料段來不及被釋放,如果正常退出,會導致vfork建立的父程序執行已經被子程序釋放的資料段,從而出現段錯誤。
}
else
{
count++;
printf("parent count = %d\n",count);
}
/************************************************************************************/
/***********************************fork.c****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("fork = %d\n",getpid());
if(argc != 3)
{
printf("Please input two param!\n");
exit(1);
}
int i;
for(i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n",i,argv[i]);
}
pid_t pid;
/*此時僅有一個程序,*/
int count = 0;
pid = fork();
/*此時已經有兩個程序在運行了*/
if(pid < 0)%s
{
perror("fork error!");
exit(1);
}
if(pid == 0)
{
count++;
printf("child count = %d\n",count);
sleep(5);
exit(1); //
}
else
{
count++;
printf("parent count = %d\n",count);
}
/************************************hello.c****************************************/
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("hello world! = %d\n",getpid());
//execl("/root/0207/fork","./fork","hello1","hello2",NULL); 第三種建立子程序的方法
char *argv[] = {"./fork","hello1","hello2",NULL};
//execv("/root/0207/fork",argv);
system("./fork hello1 hello2"); 第四種建立子程序的方法
while(1)
{
printf("hello!\n");
sleep(1);
}
return 0;
}
/***********************************************************************************/