System 函数的实现|学习笔记

简介: 快速学习 System 函数的实现

开发者学堂课程【物联网开发- Linux 高级程序设计全套视频System 函数的实现】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:https://developer.aliyun.com/learning/course/660/detail/11005


System 函数的实现

 

内容介绍:

一、 system 函数的概述

二、 system 函数实现的流程图

三、 system 函数实现示例


一、system 函数的概述

1、功能

system 会调用 fork 函数产生子进程,子进程调用 exec 启动/bin/sh -c string 来执行参数 string 字符串代表的命令,此命令执行完后返回原调用进程。

2、参数

要执行的命令的字符串。

3、返回值

如果 command 为 NULL,则 system()函数返回非0,一般为1。

如果 system (在调用/bin/sh 时失败则返回127,其它失败原因返回-1。

4、注意

system 调用成功后会返回执行 shell 命令后的返回值。其返回值可能为1、127也可能为-1故最好应检查errno来确认执行成功。

5、提示

子进程调用 exec 启动/bin/sh-Cstring来执行参数string字符串所代表的命令,父进程等待子进程退出

 

二、流程图

image.png

流程图解析:

从创建进程以下属于 system,在 system 函数里首先要创建进程,在子进程里用exec去启动se执行命令,如果exec成功则执行命令,如果exec失败则打印出错信息退出子进程,父进程等紫禁城结束后回到循环的开始再去获取命令打印字符串。

三、System函数实现示例

写my_system.c程序,根据system说明实现system

(1)首先包含同文件

1 #include<stdio. h>

2 #include<unistd.h>

3 #include<stdlib.h>

(2)然后写根据流程图写system函数

4  Int my_ system (char *cmd_string)

5  {

6  pid_ t pid;

7

8  pid = fork() ;

9  if (pid<0)

10 {

11 return - 1;

12 }

13 else if(pid ==0)

14 {

15 execl ("/bin/sh","sh", "-C",cmd_string) ;

16 exit (127) ;

17 }

18 else

19 {

20

21 }

(3)等待父进程结束,定义一个变量

7  int status;

(4)父进程等待传一个变量

21  wait (&status)

(5)进函数前首先应判断

8  if(cmd_string==NULL)

9  return 1;

10 pid = fork()

11 if(pid<0)  

12 {

13 return -1

14 {

15 else if(pid ==0)

16 {

17 execl ("/bin/sh","sh", "-C",cmd_stringNULL3) ;

18 exit (127) ;

19 }

20 else

21 {

22 wait(&status);

23

24 }

25 return status;

26

27 }

28 int main()

29 {

30 charcmd[100] ;

31 intret ;

32 while (1 )

33 {

34 printf ("pleaseinput your cmd S") ;

35 fflush (stdout) ;

36 gets (cmd) ;

37 ret=my system(cmd) ;

38 printf("ret-adn",ret) ;

39 }

40 return 0

相关文章
|
9月前
|
小程序 Unix Shell
system()函数
system()函数
61 0
|
9月前
|
安全 Java
灵魂拷问:你真的理解System.out.println()打印原理吗?
灵魂拷问:你真的理解System.out.println()打印原理吗?
89 0
|
9月前
|
Java
System与Runtime类
System与Runtime类
33 0
|
6月前
System.exit(0)和System.exit(1)区别
System.exit(0)和System.exit(1)区别
|
8月前
print与println的区别
print与println的区别
43 0
|
8月前
|
算法 Java
System类
System类
24 0
“System.out.println(的正确格式
“System.out.println(的正确格式
87 0
|
物联网 Shell Linux
System 函数|学习笔记
快速学习 System 函数
87 0
System 函数|学习笔记
|
Java 开发者
System 类|学习笔记
快速学习 System 类
|
Java
java 标准输出与标准错误 out与 err 区别 用法 联系 java中的out与err区别 System.out和System.err的区别 System.out.println和System.err.println的区别 Java重定向System.out和System.err
本文关键词: java 标准输出与标准错误    out与 err 区别 用法 联系  java中的out与err区别  System.out和System.err的区别 System.out.println和System.
1474 0