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);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章