exec函数和system()函数

【操作系统01】C语言利用CerateProcess创建进程 转载请注明出处: CreatProcess 阅读详情





exec函数和system()函数

exec函数和system()函数

进程控制


关于这一章基本是按照书上的知识写的, 虽然不明白查了一些资料, 但是后面明白了觉得还是书上写的好, 也就没有自己太多的想法,只是整理加深印象而已, 如果只是寻找理解的朋友, 这就不是很有用了。

进程掉用exec时, 该进程执行的程序会完全替换成新的程序, 也就是直接从main函数开始重新执行。
exec调用不会创建新的进程, 所以也就不会有新的ID产生。
exec只是用磁盘上新程序替换了现在进程的堆栈, 数据段, 正文段.

fork()创造新的进程, exec创造新的程序, exit和wait返回进程终止和等待终止.
进程中每个打开文件描述符都应该在exec执行前进行关闭, 否则执行exec后这些文件描述符将继续打开而不会关闭

我觉得着这函数还是后面要用, 自己也想加深一下理解, 所以写了出来, 不想看闲麻烦的也可以跳过

#include < unistd.h>
int execl(const char *pathname, const char arg0, … /* (char) 0 */)
int execv(const char *pathname, char *const argv[]);
int execle(const char *pathname, const char *arg0, … /* (char *) 0, char *const envp[] */
int execve(const char *pathname, char *const argv[], char *const envp[]);
int execlp(const char *filename, const char *arg0, … /* (char *)0 */);
int execvp(const char *filename, char *const argv[]);
int fexecve(int fd, char *const argv[], char *const envp[]);
  1. 错误, 返回 -1; 成功, 不返回
  2. 前四个取路径名为参数。execlp()和execvp()取文件描述符为参数, 但是如果filename包含 “/”就取路径名, 否则按照PATH环境变量搜寻可执行文件(一般是shell文件)。
  3. execl(), execle(), execlp()函数最后参数以 “NULL”结尾。
  
  1. /*************************************************************************
  2. > File Name: environ_打印环境表参数.cpp
  3. > Author: Function_Dou
  4. > Mail:
  5. > Created Time: 2018年02月01日 星期四 21时58分25秒
  6. ************************************************************************/
  7. #include <stdio.h>
  8. #include "apue.h"
  9. int main(int argc, char *argv[])
  10. {
  11. int i;
  12. char **ptr;
  13. extern char **environ;
  14. for(i = 0; i < argc; i++)
  15. printf("argv[%d] : %s\n", i, environ[i]);
  16. // 输出所有的环境变量
  17. for(ptr = environ; *ptr != 0; ptr++)
  18. printf("%s\n", *ptr);
  19. exit(0);
  20. }

解释器

解释器就是#! 后面可执行的程序。
对于解释器,exec族函数是这样做的(以execl为例),如果path是指向了一个脚本,脚本的第一行以#!开头,则:以#!后面的字符串为命令,后面加上execl参数列表中指定的参数列表,这样形成了新的程序执行。

如何理解解释器呢, 我看了些资料按照自己的思路整理了下。
先创建了一个cpp文件

  
  1. /*************************************************************************
  2. > File Name: jieshiqi.cpp
  3. > Author: Function_Dou
  4. > Mail:
  5. > Created Time: 2018年02月01日 星期四 22时18分59秒
  6. ************************************************************************/
  7. #include <stdio.h>
  8. int main(int argc, char *argv[])
  9. {
  10. int i;
  11. for(i = 0; i < argc; i++)
  12. printf("argv[%d] : %s\n", i, argv[i]);
  13. return 0;
  14. }

又写了一个脚本

  
  1. #!/home/RPZ/Code/Cc++/Process/a.out Function
  2. # 这是我jieshiqi.cpp生成的a.out的位置

当然权限要设置够

  
  1. -rwxr-xr-x. 1 root root 44 2月 1 22:21 JSQ

最后运行JSQ, 结果就出来了

  
  1. [root@192 Process]# ./JSQ
  2. argv[0] : /home/RPZ/Code/Cc++/Process/a.out
  3. argv[1] : Function
  4. argv[2] : ./JSQ
  1. 开始时讲到的,exec族函数的处理是把#!后面的字符串为命令,后面加上execl参数列表中指定的参数列表,这样形成了新的程序执行
  2. execl把命令的结果是这样执行的/home/RPZ/Code/Cc++/Process/JSQ的内容是#!/home/RPZ/Code/Cc++/Process/a.out Function,则#!后面的字符串”/home/RPZ/Code/Cc++/Process/a.out”加上命令参数列表:”Function” “自身的文件./JSQ(也就是exec族传进来的第一参数)” 就形成了新的程序行:/home/RPZ/Code/Cc++/Process/a.out Function ./JSQ

还是不太清楚可以看下面的地址里讲的, 只是排面有点不好看而已
http://blog.youkuaiyun.com/yylklshmyt20090217/article/details/4217616


system() 函数

  
  1. #include <stdlib.h>
  2. int system("cosnt char *cmdstring);
  • 关于返回值

system()在实现中调用了fork(), waitpid(), exec()函数
1. fork失败或者waitpid返回除EINTR之外的出错, 则system返回 -1, 并设置errno已指示错误类型
2. exec失败, 返回值如同shell执行exit一样
3. 3个函数都成功了, system返回值是shell的终止状态

  
  1. /*************************************************************************
  2. > File Name: system_函数的实现.cpp
  3. > Author: Function_Dou
  4. > Mail:
  5. > Created Time: 2018年02月01日 星期四 22时43分18秒
  6. ************************************************************************/
  7. #include <stdio.h>
  8. #include <sys/wait.h>
  9. #include <errno.h>
  10. #include <unistd.h>
  11. #include "apue.h"
  12. int system(const char *cmdstring)
  13. {
  14. pid_t pid;
  15. int status;
  16. if(cmdstring == NULL)
  17. return 1;
  18. if((pid = fork()) < 0)
  19. status = -1;
  20. else if(pid == 0)
  21. {
  22. // shell 的-c选项是告诉shell程序读取下一个命令行参数(这里是cmdstring)作为命令输入(而不是从标准输入或者指定文件读命令);
  23. execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
  24. _exit(0);
  25. }
  26. else
  27. while(waitpid(pid, &status, 0) < 0)
  28. if(errno != EINTR)
  29. {
  30. status = -1;
  31. break;
  32. }
  33. return status;
  34. }
  35. void
  36. pr_exit(int status)
  37. {
  38. if (WIFEXITED(status))
  39. printf("normal termination, exit status = %d\n",
  40. WEXITSTATUS(status));
  41. else if (WIFSIGNALED(status))
  42. printf("abnormal termination, signal number = %d%s\n",
  43. WTERMSIG(status),
  44. #ifdef WCOREDUMP
  45. WCOREDUMP(status) ? " (core file generated)" : ""
  46. #else
  47. ""
  48. #endif
  49. );
  50. else if (WIFSTOPPED(status))
  51. printf("child stopped, signal number = %d\n", WSTOPSIG(status));
  52. }
  53. int main(void)
  54. {
  55. int status;
  56. if((status = system("date")) < 0)
  57. err_sys("system() error");
  58. pr_exit(status);
  59. if((status = system("no file")) < 0)
  60. err_sys("system() error");
  61. pr_exit(status);
  62. if((status = system("who; exit 44")) < 0)
  63. err_sys("system() error");
  64. pr_exit(status);
  65. exit(0);
  66. }
  67. /* 样列
  68. *
  69. [root@192 Process]# ./a.out
  70. 2018年 02月 01日 星期四 22:57:00 CST
  71. normal termination, exit status = 0
  72. sh: no: 未找到命令
  73. normal termination, exit status = 127
  74. root :2 2018-02-01 14:30 (:2)
  75. root pts/0 2018-02-01 20:58 (:2)
  76. root pts/1 2018-02-01 21:40 (:2)
  77. root pts/2 2018-02-01 21:56 (:2)
  78. normal termination, exit status = 44
  79. */

如果在调用system就已经有了子进程, 那么就将出问题.


nice()值的效果

这里具体只写了一个程序, 将书上的那个程序进行了解释

  
  1. /*************************************************************************
  2. > File Name: nice_调度.cpp
  3. > Author: Function_Dou
  4. > Mail:
  5. > Created Time: 2018年02月02日 星期五 11时53分18秒
  6. *************************** timeval ***********************************
  7. struct timeval
  8. {
  9. long tv_sec; //秒
  10. long tv_usec; //微秒
  11. };
  12. struct timezone
  13. {
  14. int tz_minuteswest; //和Greenwich 时间差了多少分钟
  15. int tz_dsttime; //日光节约时间的状态
  16. };
  17. *************************** gettimeofday *******************************
  18. int gettimeofday (struct timeval * tv, struct timezone * tz);
  19. gettimeofday 会把目前的时间放入tv, 结构中, 当地时区的信息则放入tz结构中.
  20. 返回值:成功则返回0,失败返回-1,错误代码存于errno。
  21. *************************** nice **************************************
  22. int nice(int inc);
  23. nice()用来改变进程的进程执行优先顺序. 参数inc 数值越大则优先顺序排在越后面, 即表示进程执行会越慢. 只有超级用户才能使用负的inc 值, 代表优先顺序排在前面, 进程执行会较快.
  24. 如果执行成功则返回0, 否则返回-1, 失败原因存于errno 中.
  25. **************************** strtol ***********************************
  26. long int strtol (const char* str, char** endptr, int base);
  27. strtol() 函数用来将字符串转换为长整型数(long)
  28. str 为要转换的字符串,endstr 为第一个不能转换的字符的指针,base 为字符串 str 所采用的进制。
  29. 当 base 的值为 0 时,默认采用 10 进制转换,
  30. 若endptr 不为NULL,则会将遇到的不符合条件而终止的字符指针由 endptr 传回;若 endptr 为 NULL,则表示该参数无效,或不使用该参数
  31. ****************************** setbuf *********************************
  32. void setbuf(FILE *stream, char *buf)
  33. 使得文件打开后, 用户可建立自己设置的缓冲区, 而不使用fopen()打开文件设定的默认缓冲区大小
  34. buf = 0. 文件I/O不带缓冲
  35. ************************************************************************/
  36. #include <stdio.h>
  37. #include "apue.h"
  38. #include <errno.h>
  39. #include <sys/time.h>
  40. // 不同系统的操作
  41. #if defined(MACOS)
  42. #include <sys/limits.h>
  43. #elif defined(SOLARIS)
  44. #include <limits.h>
  45. #elif defined(BSD)
  46. #include <sys/param.h>
  47. #endif
  48. unsigned long long count;
  49. struct timeval end;
  50. void checktime(char *str)
  51. {
  52. struct timeval tv;
  53. // 获取当前的时间放入tv里面.
  54. gettimeofday(&tv, NULL);
  55. if(tv.tv_sec >= end.tv_sec && tv.tv_usec >= end.tv_usec)
  56. {
  57. printf("%s %lld\n", str, count);
  58. exit(0);
  59. }
  60. }
  61. int main(int argc, char *argv[])
  62. {
  63. pid_t pid;
  64. char *s;
  65. int nzero, ret;
  66. int adj = 0;
  67. setbuf(stdout, NULL);
  68. #if defined(NZERO)
  69. nzero = NZERO;
  70. #elif defined(_SC_NZERO)
  71. nzero = sysconf(_SC_NZERO);
  72. #else
  73. #error NZERO undefined
  74. #endif
  75. printf("NZERO = %d\n", nzero);
  76. if(argc == 2)
  77. // 转换为对应的整形
  78. adj = strtol(argv[1], NULL, 0);
  79. // 获得当前的时间
  80. gettimeofday(&end, NULL);
  81. end.tv_sec += 10;
  82. if((pid = fork()) < 0)
  83. err_sys("fork error");
  84. else if(pid == 0)
  85. {
  86. s = "child";
  87. printf("current nice value in child is %d, adjusting by %d\n", nice(0) + nzero, adj);
  88. errno = 0;
  89. if((ret = nice(adj)) == -1 && errno != 0)
  90. err_sys("child set scheduling priority");
  91. printf("now child nice value in parent is %d\n", nice(0) + nzero);
  92. }
  93. else
  94. {
  95. s = "parent";
  96. printf("current nice value in parent is %d\n", nice(0) + nzero);
  97. }
  98. for(; ; )
  99. {
  100. if(++count == 0)
  101. err_quit("%s counter wrap", s);
  102. checktime(s);
  103. }
  104. }


C语言的多进程fork()、函数exec*()、system()与popen()函数 阅读详情

相关推荐

PHP 四个执行系统命令函数:exec()、passthru()、system()、shell_exec()

php提供4种方法执行系统外部命令:exec()、passthru()、system()、 shell_exec()。 在开始介绍前,先检查下php配置文件php.ini中是有禁止这是个函数。找到 disable_functions,配置如下: disable_functions = 如果“disable_functions=”后面有接上面四个函数,将其删除。 默认php.ini配置文件中是不禁止你调用执行外部命令的函数的。 方法一:exec() function exec(string

JineD的博客 1298

C++中的exec()函数

fork函数之后,如果想要把子进程换成一个我想要执行的进程,这时,就不得不使用exec()函数了,这也是fork()的意义所在。当然,exec系列的函数也可以将当前进程替换掉,不一定非要fork()一个子进程。常见的fork()调用例子有很多,比如从wechat发起一个语音电话、从bash或者zsh执行一个a.out程序,都是在利用exec系统调用将新产生的子进程完全替换成目标进程。int a = 0;a++;return 0;topps 54861很明显,它是zshkill 57892。

shiwei0813的博客 3409

LoRa模块选型指南:正点原子ATK-LORA-01与SX1278芯片深度评测(含实测距离/功耗数据)

本文深度评测了正点原子ATK-LORA-01与SX1278芯片的性能表现,通过实测数据展示其在复杂环境中的通信距离与功耗表现。特别适合智慧农业、工业监测等物联网应用场景,提供详细的配置指南和优化技巧,帮助开发者实现高效、低功耗的LoRa通信解决方案。

weixin_29191081的博客 290

[c/c++]6. exec函数

exec image.png 曾提及用fork函数创建新的子进程后,子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程执行的程序完全替换为新程序,而新程序则从其main函数开始执行。因为调用exec并不创建新进程,所以前后的进程ID并未改变。exec只是用磁盘 上的一个新程序替换了当前进程的正文段、数据段、堆段和栈段。 有7种不同的e...

Escaping 3402

Hadoop生态系统-新手快速入门(含HDFS、HBase系统架构)

Hadoop简介 Hadoop是一个由Apache基金会所开发的分布式系统基础架构。 用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。 Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS。HDFS有高容错性的特点,并且设计用来部署在低廉的(low-cost)硬件上;而且它提供高吞吐量...

Hadoop环境搭建教程 472

Windows系统的Mamba环境配置详细教程(状态空间模型)

causal_conv1d也是安装mamba的依赖必须库。安装完成后,通过pip list可以查看到安装的库。Triton是安装mamba的依赖,需要先安装。上述工作准备好后,按下面步骤安装。直接根据离线文件安装即可。是自己的虚拟环境名字。

2301_77831163的博客 3677

C/C++如何启动外部可执行程序(exe)

本文将介绍四种启动外部可执行程序的方法,排版不分优先级,实际应用中需根据需求选择最合适的方法。

old_cai_niao_new的博客 3346

脑机接口技术介绍、应用与挑战

脑机接口的概念最先于1973年提出,伴随着计算机性能的飞速提高,在美国“人类脑计划”的资金支持下,脑机接口的研究进入了高速发展期。去年年末,我国科技部会议透露:中国将拿出540亿元,推进中国脑计划的发展。同时,这一举措也推动了我国脑机接口的研究发展。 脑机接口属于多学科交叉科技,涉及神经科学、计算机科学、认知科学、控制与信息科学技术、医学等多个学科。技术实现方式是通过信号采集设备从大脑皮层采集脑电信号,经过放大、滤波、A/D转换等处理,转换为可以被计算机识别的信号,然后对信号进行预处理,提取特征信号,再利

weixin_44603934的博客 9132

2022-1-14 牛客C++项目 —— exec函数族学习

如果在父进程函数里面使用 exec 会有什么样的结果?有什么更好的做法? 若执行成功,会造成exec函数之后的原先的进程调用的实体被新调用的进程实体替换掉,如果需要使用原先父进程之后的代码时没有可能的。 更好的方法是创建一个子进程,然后在子进程里面执行exec函数,子进程本来就是父进程的 clone ,被替换掉也没啥损失。 由下图可知,执行exec的时候将原先进程的用户区整个儿替换掉,之后再使用 a.out 的用户区接在原来进程的内核区上面。 exec函数族有哪些函数? execl () 函数学习 /.

weixin_51187533的博客 1076

在 NVIDIA DGX Spark 上运行 vLLM + Open WebUI

DGX Spark 和 GX10 都是性能强大的机器,但只有将它们视为交互式工作站而非精简版服务器,才能真正发挥它们的优势。合理利用共享资源,规划并发工作负载,并谨慎控制内存限制。做到这些,vLLM 与 Open WebUI 的结合就能成为可靠​​的日常工具,而不是脆弱的实验品。DGX平台本身价格不菲,但这并非体验此类硬件的唯一途径。多家厂商提供基于相同核心架构、价格更为亲民的系统,这些系统通常配备容量较小的固态硬盘或配置更为简化,但基本性能并未改变。

iCloudEnd的博客 1750

PCIE的MSI中断处理机制与优化策略

PCIe设备的。

xiaoheshang_123的博客 518

perl exec_Perl Array exec()和system()函数-快速教程

perl execexec(PROGRAM); $result = system(PROGRAM); Both Perl's exec() function and system() function execute a system shell command. The big difference is that system() creates a fork process and wai...

cumao2792的博客 357

java项目反编译工具记录,共计6个工具

java项目反编译工具记录,共计6个工具

橙-极纪元-JJYCheng 1801

PHP执行系统外部命令函数:exec()、passthru()、system()、shell_exec()

exec 执行系统外部命令时不会输出结果,而是返回结果的最后一行,如果你想得到结果你可以使用第二个参数,让其输出到指定的数组,此数组一个记录代表输出的一行,即如果输出结果有20行,则这个数组就有20条记录,所以如果你需要反复输出调用不同系统外部命令的结果,你最好在输出每一条系统外部命令结果时清空这个数组,以防混乱。system和exec的区别在于system在执行系统外部命令时,直接将结果输出到浏览器,不需要使用 echo 或 return 来查看结果,如果执行命令成功则返回true,否则返回false。

m0_62089210的博客 1126

Altium Designer(AD24/25)PCB编辑的几种方法介绍

本文介绍了Altium Designer(AD24/25)软件中PCB编辑的四种操作方法:1)通过菜单栏"Place→Component"激活;2)点击工具栏元器件图标;3)右键快捷菜单选择;4)快捷键P+C组合操作。建议初学者先通过菜单栏和快捷菜单熟悉操作,熟练后转为工具栏和快捷键以提高效率。文章配有操作示意图,帮助用户快速掌握PCB元器件放置技巧。

fydar的博客 944

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

PHP 执行外部命令函数:exec()、system()、passthru()、shell_exec()、popen()

PHP内置函数,提供了4种方法执行系统外部命令: exec()、system()、passthru()、 shell_exec() 查看命令函数配置 在开始介绍前,先检查下php配置文件php.ini中是有禁止这是个函数 vim /etc/php.ini或 vim /usr/local/php/lib/php.ini php.ini 默认配置文件中是不禁止你调用执行外部命令的函数的。 找到 disable_functions,正常开启的配置为disable_functions...

风口上的猪博客 2761

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[转帖]system()、exec()、fork()三个与进程有关的函数的比较

system()、exec()、fork()三个与进程有关的函数的比较 https://www.cnblogs.com/qingergege/p/6601807.html 启动新进程(system函数) system()函数可以启动一个新的进程。 int system (const char *string ) 这个函数的效果就相当于执行sh –c str...

weixin_30555125的博客 108

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

exec 族函数 和 system()函数

我们用fork函数创建新进程后,经常会在新进程中调用exec函数去执行另外一个程序。当进程调用exec函数时,该进程被完全替换为新程序。因为调用exec函数并不创建新进程,所以前后进程的ID并没有改变。

weixin_73901182的博客 795

多进程函数系列fork(), wait(), exec()系列,system(), posix_spawn()实例详解

多进程函数系列fork(), wait(), exec()系列,system(), posix_spawn()实例详解

Be The Best! 8357

PHP 执行系统外部命令的函数- system() exec() passthru()

PHP 执行系统外部命令的函数: system() exec() passthru()区别:system() 输出并返回最后一行shell结果。exec() 不输出结果,返回最后一行shell结果,所有结果可以保存到一个返回的数组里面。passthru() 只调用命令,把命令的运行结果原样地直接输出到标准输出设备上。相同点:都可以获得命令执行的状态码 demo: //system('dir...

weixin_33974433的博客 186

【php】PHP执行系统外部命令函数:exec()、passthru()、system()、shell_exec()

php提供4种方法执行系统外部命令:exec()、passthru()、system()、 shell_exec()。在开始介绍前,先检查下php配置文件php.ini中是有禁止这是个函数。找到 disable_functions,配置如下: disable_functions = 如果“disable_functions=”后面有接上面四个函数,将其删除。默认php.ini配置文件中是不...

weixin_30407613的博客 127

PHP中不能使用exec(),system(),shell_system()等函数的解决方法

PHP中不能使用exec(),system(),shell_system()等函数的解决方法。 Windows+IIS环境下,由于权限的设置一般不能执行exec(),system(),shell_system()这三个函数,一...

cjqbk811121的博客 661

exec族函数、system()函数和popen函数

exec族函数: exec族函数的作用: (1)一个父进程希望复制自己,使父子进程同时执行不同的代码段,如父进程等待客户端的服务请求。当这种请求到达时,父进程嗲用fork(),使子进程处理次请求,父进程则继续等待下一个服务请求到达。 (2)一个进程要执行一个不同的程序。在这种情况下,子进程fork返回后立即调用exec。 int execl(const char *path, const char *arg, ...); int execlp(const char *file,

没实力的码农写的渣渣博客 514

PHP中三个调用系统命令的函数system(),exec(),passthru()比较

PHP中三个调用系统命令的函数system(),exec(),passthru()比较 我们知道*php*给我们提供了*system()*,*exec()*,*passthru()*这三个函数来调用外部的命令. 虽然*这三个命令都能执行linux系统的shell命令,*但是其实他们是有区别的: system() 输出并返回最后一行shell结果。 exec() 不输出结果,返回最后一行s

stone学习笔记 1084
上一篇: apue.h头文件
下一篇: 进程关系
Function_18
博客等级 码龄10年 193粉丝 239原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值