Linux下利用fork / execvp过程在子进程中执行小程序

1、派生进程的创建

#include<unistd.h>
pid_t fork(void);

 

pid_t vfork(void);

 

调用fork时,系统将创建一个与当前进程相同的新的进程,将原有的进程称为父进程,新生成的进程称为子进程,子进程获得和父亲进程相同的数据,但是同父进程使用不同的数据段和堆栈段。将从父进程和子进程中分别返回,从父进程中返回子进程的PID,从子进程返回值0。调用出错时,返回值为-1,并将error设为相应值。

vfork的作用与fork的基本相同,vfork和父进程共享数据段。vfork通常与exec函数连用,创建执行另一个程序的新进程。调用vfork时,父进程被挂起,子进程运行至调用exec函数族或调用exit时解除这种状态。

2、创建执行其他程序的进程

 

#include<unistd.h>
int execl(const char *pathname,const char *arg, ...);
int execlp(const char *filename,const char *arg, ...);
int execle(const char *pathname,const char *arg, ...,char *const envp[]);
int execv(const char *pathname,const char *argv[]);
int execvp(const char *filename,const char *argv[]);

 

int execve(const char *pathname,const char *argv[],char *const envp[]);

函数名中含有字母“l”的函数,参数个数不定,其参数由所调用程序的命令行参数列表组成,最后一个NULL表示结束。

函数名中含有字母“v”的函数,使用一个字符串数组指针argv指向参数列表,以NULL结束。

函数名中含有字母“p”的函数,自动在环境变量PATH指定的路径中搜索要执行的程序,第一个参数filename 表示可执行函数的文件名。

函数名中含有字母“e”的函数,多一个参数envp,该参数是字符串数组指针,用于指定环境变量。必须以NULL结束。

 

下面提供一个创建子进程,并调用execvp函数执行另一个小程序的例子:

 

forkexecvp.cpp

#include<sys/types.h>

#include<stdio.h>

#include<unistd.h>

#include<cstdlib>

intmain(int argc,char*argv[])

{

        pid_t pid;

        if((pid=vfork())<0)

        {

                printf("forkerror!\n");

                exit(1);

        }

        argv++;

        if(pid==0)

        {

                printf("Child process PID:%d.\n",getpid());

                if(execvp(*argv,argv)==-1)

                {       perror("execvp");

                        printf("No suchfile!");

                        exit(0);

                }

                printf("Parent processPID: %d.\n",getpid());

        }

}

 

hello.c

 

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

int main()

{

    printf("Hello World!");

    return 0;

}

输入:gcc forkexecp.cc

        ./a.exe ./hello.c

输出: child process PID :xxxxx

            Hello  World!

注意:这里父进程号是不会输出的,因为程序转到另一个可执行程序了,除非execvp调用失败时才会执行父进程号的输出

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值