26.1 system 函数
26.1.1 函数说明
system(执行shell 命令)
相关函数 fork,execve,waitpid,popen
1 #include <stdlib.h>
2int system(constchar * string);
- 函数功能:简化 exec 函数
- 函数说明
- system()会调用 fork() 产生子进程,由子进程来调用 /bin/sh -c string 来执行参数 string 字符串所代表的命令,此命令执行完后随即返回原调用的进程。
- 在调用 system() 期间 SIGCHLD 信号会被暂时搁置,SIGINT 和 SIGQUIT 信号则会被忽略。
- 等同于 /bin/bash -c "cmd" 或者 exec("bash", "-c", "cmd")
- 返回值
- 如果 system()在调用 /bin/sh 时失败则返回 127,其他失败原因返回-1。
- 若参数 string 为空指针(NULL),则返回非零值。
- 如果system()调用成功则最后会返回执行 shell 命令后的返回值,但是此返回值也有可能为 system()调用 /bin/sh 失败所返回的 127,因此最好能再检查 errno 来确认执行成功。
- 附加说明
- 在编写具有SUID/SGID权限的程序时请勿使用 system(),system() 会继承环境变量,通过环境变量可能会造成系统安全的问题。
26.1.2 system 应用
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 5char *cmd = "date";
6 7int main(void)
8{
9 system("clear");
10 system(cmd);
1112return0;
13 }
编译执行
26.1.3 构建 mysystem 命令
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5 #include <sys/wait.h>
6 7char *cmd1 = "date > s1.txt";
8char *cmd2 = "date > s2.txt";
910void mysystem(char *cmd)
11{
12 pid_t pid;
13if((pid = fork()) < 0) {
14 perror("fork error");
15 exit(1);
16 } elseif(pid == 0) {
17if(execlp("/bin/bash", "/bin/bash", "-c", cmd ,NULL) < 0) {
18 perror("execlp error");
19 exit(1);
20 }
21 }
2223 wait(0);
24}
2526int main(void)
27{
28 system("clear");
29 system(cmd1);
3031 mysystem(cmd2);
3233return0;
34 }
编译调试
26.6 进程状态切换
- runnable:就绪状态
- running:运行状态
- block/suspend:阻塞或挂起状态
- dead:终止状态。正在运行的状态调用 return/exit_exit 进入 dead 状态
- os scheduler:系统调度
原文:https://www.cnblogs.com/kele-dad/p/9157864.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!