system、 exec函数族、fork函数用法说明

system(), exec函数族, fork函数用法说明

启动一个新线程的方式:

  • system()

    该函数经常用来在C程序中调用shell脚本或者命令行程序.

    特点:

    效率低下,首先需要创建一个shell, 然后配置shell环境,之后再执行相应的命令。

    对shell环境的依赖很大。

  • exec() 函数族

    也用来创建新的进程,但会替换原先的进程

    int execl(const char *path, const char *arg0, …, (char *)0);

    int execp(const char *file, const char *arg0, …, (char *)0);

    int execle(const char *path, const char *arg0, …, (char *)0, char *const envp[]);

    int execv(const char *path, const char *argv[]);

    int execvp(const char *file, const char *argv[]);

    int execve(const char *path, const cha *argv[], char *const envp[])

  • fork()

    复制原先的进程环境,从而创建一个新的子进程0

示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include "../main/basic_utilits.h"

void system_demo()
{
    printf("Run a script file in C envirenment\n");
    system("../shell/mkPasswd.sh 10");
    system("ps aux | awk '{print $11}' | sort | uniq -c | sort -nr | awk '{print $2}' | head");
    printf("shell script over\n");
}

void exec_funcs()
{
    char *const ps_argv[] = 
    {"ps", "ax", 0};
    
    char *const ps_envp[] = 
    {"PATH=/bin:/usr/bin:/usr/local/bin:/sbin", "TERM=console", 0};

    execl("/bin/ps", "ps", "-ax", NULL);
    execlp("ps", "ps", "ax", NULL);
    execle("/bin/ps", "ps", "ax", NULL, ps_envp);

    execv("/bin/ps", ps_argv);
    execvp("ps", ps_argv);
    execve("/bin/ps", ps_argv, ps_envp);
}

void fork_demo()
{
    pid_t pid;
    int exit_code = 0;
    char *message = NULL;
    int count = 0;
    int i = 0;
    pid = fork();
    switch(pid){
        case -1:
            printf("fork_demo: fork error\n");
            break;
        case 0:
            exit_code = 37;
            count = 10;
            message = "This is child process\n";
            break;
        default:
            exit_code = 0;
            count = 5;
            message = "This is parent process\n";
            break;

    }
    for(i=0;i<count;i++){
        printf("%s", message);
        my_msleep(500);
    }

    if(pid){
        int stat_child = 0;
        pid_t child_pid;
        //child_pid = wait(&stat_child); //获取的退出码需要使用特定的宏函数进行操作
        waitpid(pid, &stat_child, 0);
        printf("child pid : %d  stat_code: %d\n", pid, WEXITSTATUS(stat_child));
    }
    printf("exit code : %d\n", exit_code);
    exit(exit_code);
}

posted @ 2020-05-05 22:45  叨陪鲤  阅读(95)  评论(0编辑  收藏  举报