C++中执行shell命令,popen与system的区别_c++ popen_Op_chaos的博客-CSDN博客
https://cplusplus.com/reference/cstdlib/system/
2.system
system()函数执行过程:
1.fork一个子进程;
2.在子进程中调用exec函数去执行command;
3.在父进程中调用wait去等待子进程结束。
由于system没有新开shell,执行system的随后会调用waitpid,来等待子进程运行完毕,所以会阻塞的。
———————————
- #include
- #include
-
- int main()
- {
- system("./test");
- printf("exit\n");
- }
kill -9 父进程
父进程退出,子进程不会退出.
Linux中system函数返回值详解-腾讯云开发者社区-腾讯云
Linux下C语言 system函数返回值「建议收藏」 - 全栈程序员必看
system()、popen()、fork()三个函数 的区别 - 代码先锋网
- cat test.sh
- #!/bin/bash
- ta10()
- {
- echo "函数要退出咯"
- return 1
- echo "函数没退出成功吗?"
- }
- ta10
- ./test 1
- echo "脚本要退出咯"
- #exit 1 # system 返回失败..
- exit # system 返回成功..
- echo "脚本没退出成功吗?"
-
- # return 0
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/wait.h>
- #include <sys/types.h>
-
- int main()
- {
- pid_t status;
-
-
- status = system("./test.sh");
-
- if (-1 == status)
- {
- printf("system error!");
- }
- else
- {
- printf("exit status value = [0x%x]\n", status);
-
- if (WIFEXITED(status))
- {
- if (0 == WEXITSTATUS(status))
- {
- printf("run shell script successfully.\n");
- }
- else
- {
- printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status));
- }
- }
- else
- {
- printf("exit status = [%d]\n", WEXITSTATUS(status));
- }
- }
-
- return 0;
- }