exec函数族

 

 

/*
    exec函数族
        加载并运行可执行目标文件
        fork调用一次,返回两次
        exec调用一次,从不返回,只有出现错误时,才会返回-1到调用程序
        fork后相同程序,不同进程;execve后相同进程,不同程序。
        因此,通常fork一个子进程,然后再使用exec

        #include <unistd.h>

        int execl(const char *path, const char *arg, ...);
            参数:
                path:文件路径
                arg:参数列表
                    第一个参数一般为执行程序的名称
                    最后一个参数以NULL结束
        int execlp(const char *file, const char *arg, ...);
            从环境变量中查找指定的可执行文件,如果找到了就执行,找不到就不执行
            参数:
                file:文件名,不是路径



*/

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

int main()
{

    pid_t pid = fork();
    if(pid == 0)
    {
        // execl("dir", "dir", NULL); // 运行自己的程序
        execl("/bin/ps", "ps", "aux", NULL); // 运行系统的程序
        printf("In the Child process\n");
    }   
    else if(pid > 0)
    {
        printf("In the parent process\n");
    }

    for(int i = 0; i < 10; i++)
    {
        printf("%d\n", i);
    }


    return 0;
}

 

posted @ 2023-04-27 19:13  WTSRUVF  阅读(15)  评论(0编辑  收藏  举报