Chinaunix首页 | 论坛 | 博客
  • 博客访问: 238181
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: 嵌入式

2012-09-05 21:43:15

附:(system()函数相关)

1、相关函数  

      fork,execve,waitpid,popen  

2、表头文件  

       #include  

3、定义函数  

      int system(const char * string);  

4、函数说明  

       system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。  

5、返回值  

       如果fork()失败 返回-1:出现错误   如果exec()失败,表示不能执行Shell,返回值相当于Shell执行了exit(127)  如果执行成功则返回子Shell的终止状态   如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),则返回非零值>。 如果system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为 system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。

程序要求:

      了解system()函数的实现方式,采用自己的方式实现system()函数的功能;


程序如下:


点击(此处)折叠或打开

  1. #include <stdio.h>
  2.     #include <stdlib.h>
  3.     #include <string.h>
  4.     #include <unistd.h>
  5.     #include <errno.h>
  6.       
  7.     int system_test(const char *cmdstring)
  8.     {
  9.         pid_t pid;
  10.         int status;
  11.       
  12.         if (cmdstring == NULL)
  13.             return 1;
  14.           
  15.         if ((pid = fork()) < 0)
  16.             status = -1;
  17.         else if (pid == 0)
  18.         {
  19.             execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
  20.             _exit(127);
  21.         }
  22.         else
  23.         {
  24.             while (waitpid(pid, &status, 0) < 0)
  25.             {
  26.                 if (errno != EINTR)
  27.                 {
  28.                    status = -1;
  29.                    break;
  30.                 }
  31.             }
  32.         }
  33.       
  34.         return status;
  35.     }
  36.       
  37.     int main(int argc, const char *argv[])
  38.     {
  39.         system_test("date");
  40.           
  41.         return 0;
  42.     }

阅读(1489) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~