linux c编程system与exec等区别简介

来源:互联网 发布:微信刷票软件免费版 编辑:程序博客网 时间:2024/06/07 20:42

//首先来看一个示例:
#include <stdio.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <stdlib.h>

int main()

{

  int status;

  if((status=system("date"))<0){

    printf("system error.\n");

    exit(0);

  }
  printf("exit status=%d\n", status);

  if((status=system("nosuchcommand"))<0){

    printf("system error.\n");

    exit(0);

  }
  printf("exit status=%d\n", status);
  if((status=system("who;exit 44"))<0){

    printf("system error.\n"); 
    exit(0);

  }

  printf("exit status=%d\n", status);

  exit(0);
}

输出如下:

2012年 03月 17日 星期六 12:15:20 CST

exit status=0

sh: nosuchcommand: not found

exit status=32512

fanglin  tty7         2012-03-17 08:57 (:0)

fanglin  pts/0        2012-03-17 08:58 (:0.0)
exit status=11264

说明:

system函数调用来完成命令行的执行,而不直接用fork和exec,是因为system函数中进行了必须的错误处理和信号处理,更有利于编程。
在此,exec实现方法略过,有兴趣朋友可以试试用exec来实现看下效果。

 

system实际上还是fork+exec函数来执行外部程序,我伙来看现system的实现代码#include <sys/types.h>

#include <sys/wait.h>

#include <errno.h>

#include <unistd.h>

int system(const char *cmdstring)

{

 pid_t pid; 

 int status;

 if(cmdstring==NULL){ return(1); }

if((pid=for())<0){ status=-1;

}else if(pid==0){ 

 execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);

 _exit(127); //不使用exit是为了保证进程的标准I/O流不被清掉

}else{
 while(waitpid(pid, &status, 0)<0)
     if(errno != EINTR){ status=-1; break; }
}
return(status);
}

0 0
原创粉丝点击