system、 exec函数族、fork函数用法说明
发布日期:2021-06-23 04:43:41 浏览次数:7 分类:技术文章

本文共 1663 字,大约阅读时间需要 5 分钟。

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 
#include
#include
#include
#include
#include
#include
#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

转载地址:https://blog.csdn.net/s2603898260/article/details/105940774 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:2012元旦泰山观日
下一篇:2011年6月云南行

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年03月30日 19时11分28秒