execl替换进程__2018.06.14

代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    pid_t pid;
    pid=fork();
    if(0==pid)
    {
        printf("这是子线程,pid=%d\n",getpid());
        execl("/bin/ls","ls","-l",NULL);
    }
    else if(pid>0)
    {
        printf("这是父线程,pid=%d\n",getpid());
        pid_t ret=wait(NULL);//不管心进程退出状态
        printf("父进程返回\n");
        sleep(1);
        if(ret==pid)
        {
            printf("wait success\n");
        }
        else
        {
            printf("wait failed!\n");
        }
    }
    else
    {
        fprintf(stderr,"ERROR:fork() failed!\n");
    }
    return 0;
}

#include<stdio.h>

int main()
{
    char *const argv[] = { "ps", "-ef", NULL};
    char *const envp[] = {"PATH=/bin:/usr/bin", "TERM=console", NULL};

    execl("/bin/ps", "ps", "-ef", NULL);

   //带p的,可以使用环境变量PATH,无需写全路径
    execlp("ps", "ps", "-ef", NULL);

   //带e 的,需要自己组装环境变量
    execle("ps", "ps", "-ef", NULL, envp);

    execv("/bin/ps", argv);

   //带p的,可以使用环境变量PATH,无需写全路径
    execvp("ps", argv);

   //带e的,需要自己组装环境变量
    execve("/bin/ps", argv, envp);

    exit(0);
}

猜你喜欢

转载自blog.csdn.net/weixin_40316053/article/details/80699836
今日推荐