linux下system函数详解

版权声明:本文为博主原创文章,未经博主允许可以转载。 https://blog.csdn.net/yaowangII/article/details/82997102

一、system函数的简单介绍

头文件 
 #include <stdlib.h>

函数定义
 int system(const char * string); 

函数说明

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

二、system函数的返回值

status = system("./test.sh")

1、先统一两个说法:
(1)system返回值:指调用system函数后的返回值,比如上例中status为system返回值
(2)shell返回值:指system所调用的shell命令的返回值,比如上例中,test.sh中返回的值为shell返回值。

2、man中对于system的说明

   RETURN VALUE       
   The value returned is -1 on error (e.g.  fork() failed), and the return    status  of  the command otherwise. 
   This latter return status is in the       format specified in wait(2).  Thus, the exit code of the  command 
   will   be  WEXITSTATUS(status).   In  case  /bin/sh could not be executed, the exit status will be that of a
   command that does exit(127).

system函数对返回值的处理,涉及3个阶段:
阶段1:创建子进程等准备工作。如果失败,返回-1。
阶段2:调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。system的man中只说明了会写了127这个值,但实测发现还会写126等值。
阶段3:如果shell脚本正常执行结束,将shell返回值填到status的低8~15比特位中。

只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。比如:不管shell脚本中返回什么原因值,是0还是非0,都算正常执行结束。即使shell脚本不存在或没有执行权限,也都算正常执行结束。如果shell脚本执行过程中被强制kill掉等情况则算异常结束。如何判断阶段2中,shell脚本是否正常执行结束呢?系统提供了宏:WIFEXITED(status)。如果WIFEXITED(status)为真,则说明正常结束。如何取得阶段3中的shell返回值?你可以直接通过右移8bit来实现,但安全的做法是使用系统提供的宏:WEXITSTATUS(status)。

由于我们一般在shell脚本中会通过返回值判断本脚本是否正常执行,如果成功返回0,失败返回正数。所以综上,判断一个system函数调用shell脚本是否正常结束的方法应该是如下3个条件同时成立:
(1)-1 != status
(2)WIFEXITED(status)为真
(3)0 == WEXITSTATUS(status)

#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;
  }

为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作:
1.fork一个子进程;
2.在子进程中调用exec函数去执行command;
3.在父进程中调用wait去等待子进程结束。

对于fork失败,system()函数返回-1。 如果exec执行成功,也即command顺利执行完毕,则返回command通过exit或return返回的值。 (注意,command顺利执行不代表执行成功,比如command:“rm debuglog.txt”,不管文件存不存在该command都顺利执行了) 如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在,system()函数返回127. 如果command为NULL,则system()函数返回非0值,一般为1.

看完这些,我想肯定有人对system()函数返回值还是不清楚,看源码最清楚,下面给出一个system()函数的实现:

int system(const char * cmdstring) 
{ 
	pid_t pid;  
    int status; 
    if(cmdstring == NULL) 
    { 
       return (1); //如果cmdstring为空,返回非零值,一般为1 
    } 
    if((pid = fork())<0) 
    { 
       status = -1; //fork失败,返回-1 
    } else if(pid == 0)     
    { 
		execl("/bin/sh", "sh", "-c", cmdstring, (char *)0); 
        _exit(127); // exec执行失败返回127,注意exec只在失败时才返回现在的进程,成功的话现在的进程就不存在啦~~
    } 
    else //父进程 
    {
        while(waitpid(pid, &status, 0) < 0) 
	   { 
			if(errno != EINTR) 
		    { 
				 status = -1; //如果waitpid被信号中断,则返回-1 
				 break; 
		    } 
	   } 
     } 
   return status; //如果waitpid成功,则返回子进程的返回状态 
 } 

三、调用system函数的问题

先看一下问题 简单封装了一下system()函数:

int pox_system(const char *cmd_line) 
{ 
	return system(cmd_line); 
} 

函数调用:

int ret = 0; 
ret = pox_system("gzip -c /var/opt/I00005.xml > /var/opt/I00005.z"); 
if(0 != ret) 
{ 
 	Log("zip file failed\n"); 
}

问题现象:每次执行到此处,都会zip failed。而单独把该命令拿出来在shell里执行却总是对的,事实上该段代码已运行了很长时间,从没出过问题。
分析log时,我们只能看到“zip file failed”这个我们自定义的信息,至于为什么fail,毫无线索。 那好,我们先试着找出更多的线索:

 int ret = 0; 
 ret = pox_system("gzip -c /var/opt/I00005.xml > /var/opt/I00005.z"); 
 if(0 != ret) 
 { 
 	Log("zip file failed: %s\n", strerror(errno)); //尝试打印出系统错误信息 
 } 

我们增加了log,通过system()函数设置的errno,我们得到一个非常有用的线索:system()函数失败是由于“ No child processes”。
我们通过上面的线索,知道system()函数设置了errno为ECHILD,然而从system()函数的man手册里我们找不到任何有关EHILD的信息。我们知道system()函数执行过程为:fork()->exec()->waitpid(). 很显然waitpid()有重大嫌疑,我们去查一下man手册,看该函数有没有可能设置

ECHILD: ECHILD (for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) 
does not exist or is not a child of the calling process. (This can happen for one's own child if the action for 
SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.) 

果然有料,如果SIGCHLD信号行为被设置为SIG_IGN时,waitpid()函数有可能因为找不到子进程而报ECHILD错误。似乎我们找到了问题的解决方案:在调用system()函数前重新设置SIGCHLD信号为缺省值,即signal(SIGCHLD, SIG_DFL)。

system()函数之前没出错,是因为systeme()函数依赖了系统的一个特性,那就是内核初始化进程时对SIGCHLD信号的处理方式为SIG_DFL,这是什么什么意思呢?即内核发现进程的子进程终止后给进程发送一个SIGCHLD信号,进程收到该信号后采用SIG_DFL方式处理,那么SIG_DFL又是什么方式呢?SIG_DFL是一个宏,定义了一个信号处理函数指针,事实上该信号处理函数什么也没做。这个特性正是system()函数需要的,system()函数首先fork()一个子进程执行command命令,执行完后system()函数会使用waitpid()函数对子进程进行收尸。 通过上面的分析,我们可以清醒的得知,system()执行前,SIGCHLD信号的处理方式肯定变了,不再是SIG_DFL了,至于变成什么暂时不知道,事实上,我们也不需要知道,我们只需要记得使用system()函数前把SIGCHLD信号处理方式显式修改为SIG_DFL方式,同时记录原来的处理方式,使用完system()后再设为原来的处理方式。

问题分析到这里,解决方法也清晰了,于是我们修改了我们的pox_system()函数:

typedef void (*sighandler_t)(int); 
int pox_system(const char *cmd_line) 
{ 
 int ret = 0;     
 sighandler_t old_handler;     
 old_handler = signal(SIGCHLD, SIG_DFL);     
 ret = system(cmd_line);     
 signal(SIGCHLD, old_handler);     
 return ret;     
} 

四、了解popen函数

标准I/O函数库提供了popen函数,它启动另外一个进程去执行一个shell命令行。
这里我们称调用popen的进程为父进程,由popen启动的进程称为子进程。
popen函数还创建一个管道用于父子进程间通信。父进程要么从管道读信息,要么向管道写信息,至于是读还是写取决于父进程调用popen时传递的参数。下在给出popen、pclose的定义。

#include <stdio.h>
/*
函数功能:popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c来执行参数command的指令。
        参数type可使用“r”代表读取,“w”代表写入。
        依照此type值,popen()会建立管道连到子进程的标准输出设备或标准输入设备,然后返回一个文件指针。
        随后进程便可利用此文件指针来读取子进程的输出设备或是写入到子进程的标准输入设备中
返回值:若成功则返回文件指针,否则返回NULL,错误原因存于errno中
*/
FILE * popen( const char * command,const char * type);

/*
函数功能:pclose()用来关闭由popen所建立的管道及文件指针。参数stream为先前由popen()所返回的文件指针
返回值:若成功返回shell的终止状态(也即子进程的终止状态),若出错返回-1,错误原因存于errno中
*/
int pclose(FILE * stream);

下面通过例子看下popen的使用:

假如我们想取得当前目录下的文件个数,在shell下我们可以使用:

ls | wc -l

我们可以在程序中这样写:

/*取得当前目录下的文件个数*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>

#define MAXLINE 1024

int main()
{
	char result_buf[MAXLINE], command[MAXLINE];
	int rc = 0; // 用于接收命令返回值
	FILE *fp;

	/*将要执行的命令写入buf*/
	snprintf(command, sizeof(command), "ls ./ | wc -l");

	/*执行预先设定的命令,并读出该命令的标准输出*/
	fp = popen(command, "r");
	if(NULL == fp)
	{
		perror("popen执行失败!");
		exit(1);
	}
	while(fgets(result_buf, sizeof(result_buf), fp) != NULL)
	{
		/*为了下面输出好看些,把命令返回的换行符去掉*/
		if('\n' == result_buf[strlen(result_buf)-1])
		{
			result_buf[strlen(result_buf)-1] = '\0';
		}
		printf("命令【%s】 输出【%s】\r\n", command, result_buf);
	}

	/*等待命令执行完毕并关闭管道及文件指针*/
	rc = pclose(fp);
	if(-1 == rc)
	{
		perror("关闭文件指针失败");
		exit(1);
	}
	else
	{
		printf("命令【%s】子进程结束状态【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
	}

	return 0;
}

编译并执行:
$ gcc popen.c

$ ./a.out

命令【ls ./ | wc -l】 输出【2】

命令【ls ./ | wc -l】子进程结束状态【0】命令返回值【0】

上面popen只捕获了command的标准输出,如果command执行失败,子进程会把错误信息打印到标准错误输出,父进程就无法获取。比如,command命令为“ls nofile.txt” ,事实上我们根本没有nofile.txt这个文件,这时shell会输出“ls: nofile.txt: No such file or directory”。这个输出是在标准错误输出上的。通过上面的程序并无法获取。

注:如果你把上面程序中的command设成“ls nofile.txt”,编译执行程序你会看到如下结果:

$ gcc popen.c

$ ./a.out

ls: nofile.txt: No such file or directory

命令【ls nofile.txt】子进程结束状态【256】命令返回值【1】

需要注意的是第一行输出并不是父进程的输出,而是子进程的标准错误输出。

有时子进程的错误信息是很有用的,那么父进程怎么才能获取子进程的错误信息呢?

这里我们可以重定向子进程的错误输出,让错误输出重定向到标准输出(2>&1),这样父进程就可以捕获子进程的错误信息了。例如command为“ls nofile.txt 2>&1”,输出如下:

命令【ls nofile.txt 2>&1】 输出【ls: nofile.txt: No such file or directory】

命令【ls nofile.txt 2>&1】子进程结束状态【256】命令返回值【1】

五、用来popen函数代替system函数

int my_system(const char * cmd) 
{ 
    FILE * fp;     
    int res; char buf[1024]; 
    if (cmd == NULL) 
    { 
       printf("my_system cmd is NULL!\n");
       return -1;
    } 
    if ((fp = popen(cmd, "r") ) == NULL) 
    { 
       perror("popen");
       printf("popen error: %s/n", strerror(errno));
       return -1; 
    } 
   else
   {
       while(fgets(buf, sizeof(buf), fp)) 
      { 
          printf("%s", buf); 
      } 
      if ( (res = pclose(fp)) == -1) 
      { 
         printf("close popen file pointer fp error!\n"); return res;
      } 
      else if (res == 0) 
      {
          return res;
      } 
     else 
     { 
         printf("popen res is :%d\n", res);
         return res; 
     } 
   }
} 

转载出处:https://blog.csdn.net/dilireba/article/details/78645755

猜你喜欢

转载自blog.csdn.net/yaowangII/article/details/82997102