system、 exec函数族、fork函数用法说明
2024-09-08 16:12:09
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);
}
最新文章
- 导航position:absolute
- mysql大内存高性能优化方案
- URL的格式scheme
- 如何使用Git——(二)
- js执行引擎(js解释器)
- Canvas裁剪和Region、RegionIterator
- 用TTL线在CFE环境下拯救半砖wrt54g路由器
- Spring学习(12)--- @Autowired与@Resource 对比
- 简单实体类和xml文件的相互转换
- 496. Next Greater Element I
- C#+EntityFramework编程方式详细之Model First
- 小程序View内的文字不换行
- pyqt pyside QAction 代码中触发
- 阿里巴巴Java开发手册及Java代码规约扫描eclipse和IDEA插件
- linux下编写C++程序播放音频
- Codeforces 888G Xor-MST - 分治 - 贪心 - Trie
- xilinx 高速收发器Serdes深入研究-Comma码(转)
- linux安装tomcat9
- (转)C#.NET WINFORM应用程序中控制应用程序只启动一次
- mssqlservers数据嗅探
热门文章
- 就这?Spring 事务失效场景及解决方案
- Aging Cell两篇连发 | 华中科技大学王建枝团队运用蛋白质组学技术发现具有AD早期诊断价值的血小板生物标志物
- CTF中的序列化与反序列化
- badboy如何录制jmetet脚本
- Spring Cloud Alibaba - Spring Cloud Stream 整合 RocketMQ
- 如何请求一个需要登陆才能访问的接口(基于cookie)---apipost
- noip8
- AECC2018同时中英文切换多开使用,加倍提高你的工作效率
- HTML <;form>; 标签的 method 属性
- Java 方法使用