Linux进程的创建

来源:互联网 发布:手机vpn软件 编辑:程序博客网 时间:2024/05/29 15:29

1、派生进程

要创建一个进程,最基本的系统调用为fork。系统调用fork用于派生一个进程,声明格式如下:

#include<unistd.h>

pid_t fork(void);

pid_t vfork(void);

调用fork时,系统将创建一个与当前进程相同的新的进程。它与原有的进程具有相同的数据、连接关系和在同一处执行的连续性。

派生子进程示例

#include<sys/type.h>

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

int main(void)

{

pid_t pid;

if(pid=fork()<0)

{

printf("错误!!\n");

exit(1);

}

else if(pid==0)

{

printf("子进程!!\n");

}

else

{

printf("父进程!!\n");

}

exit(0);

}


调用fork函数与vfork函数的作用基本相同,但vfork并不完全复制父进程的数据段,而是和父进程共享数据段。vfork函数通常是与exec函数一起使用的,用来创建执行另一个程序的新进程。

调用vfoek函数时,父进程被挂起,子进程运行完exec函数族的函数或调用exit时解除父进程的挂起状态。

#include<sys/type.h>

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

int main(void)

{

pid_t pid;

if(pid=vfork()<0)

{

printf("错误!!\n");

exit(1);

}

else if(pid==0)

{

printf("子进程!!\n");

}

else

{

printf("父进程!!\n");

}

exit(0);

}

这里的vfork创建与上述fork代码基本相同,但是其运行结果是不同的,fork创建的进程其运行结果是动态的,而vfork创建的进程其运行结果是固定的。

使用vfork,运行结果总是子进程先返回,因为在调用vfork时付进程挂起。

2、创建执行其他程序的进程————使用exec函数

      #include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
        pid_t pid;
        if((pid=vfork())<0)
        {
        printf("vfork error!\n");
        exit(1);
        }
        else if(pid==0)
        {
        printf("child process PID:%d\n",getpid());
        setenv("PS1","CHILD\\$",1);
        printf("Process%4d:calling exec.\n",getpid());
        if(execl("/bin/sh","/bin/sh","arg2",NULL)<0)
        {
        printf("Process%4d:execl error!\n",getpid());
      exit(0);
        }
 }
        printf("Process%4d:You should never see this because the child is already gone.\n",getpid());
        printf("Process%4d:The child process is exiting!.\n");
        }
        else
        {
        printf("Parent process PID:%d.\n",getpid());
        printf("Process%4d:The parent has fork process %d.\n",pid);
      printf("Process%4d:The child has called exec or has exited.\n",getpid());
        }
        return 0;
}

3、Linux系统特有的调用_ _clone

#include<sched.h>

int _ _clone(int (*fn) (void *arg), void *child_stack,int flags,void *arg) ;

fn——函数指针,指向要执行的函数。

child_stdck——子进程堆栈段的指针。

flags——表示不同继承内容的标识。


flags标识的选取

CLONE_VM——继承父进程的虚拟存储器属性

CLONE_FS——继承父进程的chroot(根目录)、chdir(当前目录)、umask(权限掩码)

CLONE_FILES——继承父进程的文件描述符

CLONE_PID——继承父进程的文件锁、进程号及时间片

CLONE_SIGHAND—— 继承父进程的信号处理程序                                                                               


0 0