linux操作系统编程——system函数的实现

程序要求:

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


程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int system_test(const char *cmdstring)
{
    pid_t pid;
    int status;

    if (cmdstring == NULL)
        return 1;
    
    if ((pid = fork()) < 0)
        status = -1;
    else if (pid == 0)
    {
        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        _exit(127);
    }
    else
    {
        while (waitpid(pid, &status, 0) < 0)
        {
            if (errno != EINTR)
            {
               status = -1;
               break;
            }
        }
    }

    return status;
}

int main(int argc, const char *argv[])
{
    system_test("date");
    
    return 0;
}

附:(system()函数相关)

1、相关函数  

      fork,execve,waitpid,popen  

2、表头文件  

       #include<stdlib.h>  

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 来确认执行成功。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章