【问题标题】:Changing the use of system to Fork and exec in C将系统的使用更改为 C 中的 Fork 和 exec
【发布时间】:2011-10-24 15:41:54
【问题描述】:

我正在编写一个 C 程序,它需要一定数量的输入并将它们作为系统命令运行。其余的被传递到 shell 执行。但是有人建议我应该尝试使用 fork 和 exec 来运行命令。不过,我对如何实现这一点感到困惑。

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

#define MAX_BUFFER 1024                        // max line buffer
#define MAX_ARGS 64                            // max # args
#define SEPARATORS " \t\n"                     // token sparators

extern char **environ;
/*******************************************************************/

int main (int argc, char ** argv)
{
char linebuf[MAX_BUFFER];                  // line buffer
char cmndbuf[MAX_BUFFER];                  // command buffer
char * args[MAX_ARGS];                     // pointers to arg strings
char ** arg;                               // working pointer thru args
char * prompt = "==>" ;                    // shell prompt

// keep reading input until "quit" command or eof of redirected input 

while (!feof(stdin)) { 

// get command line from input


    fputs (prompt, stdout);                // write prompt
    fflush(stdout);
    if (fgets(linebuf, MAX_BUFFER, stdin )) { // read a line

// tokenize the input into args array

        arg = args;
        *arg++ = strtok(linebuf,SEPARATORS);   // tokenize input
        while ((*arg++ = strtok(NULL,SEPARATORS)));
                                           // last entry will be NULL 

        if (args[0]) {                     // if there's anything there

            cmndbuf[0] = 0;                // set zero-length command string

// check for internal/external command 

            if (!strcmp(args[0],"clr")) {  // "clr" command
                strcpy(cmndbuf, "clear");
            } else
            if (!strcmp(args[0],"cd"))
            {
                int ret;
                if (!args[1])
                    strcpy(cmndbuf, "pwd");
                ret = chdir(args[1]);
                strcpy(cmndbuf, "pwd");


            }else
            if (!strcmp(args[0],"dir")) {  // "dir" command
                strcpy(cmndbuf, "ls -al ");
                if (!args[1])
                    args[1] = ".";         // if no arg set current directory
                strcat(cmndbuf, args[1]);
            } else
            if (!strcmp(args[0],"environ")) { // "environ" command
                char ** envstr = environ;
                while (*envstr) {            // print out environment
                    printf("%s\n",*envstr);
                    envstr++;
                }                            // (no entry in cmndbuf)
            } else
            if (!strcmp(args[0],"quit")) {   // "quit" command
                break;
            } else {                         // pass command on to OS shell
                int i = 1;
                strcpy(cmndbuf, args[0]);
                while (args[i]) {
                    strcat(cmndbuf, " ");
                    strcat(cmndbuf, args[i++]);
                }
            }

// pass any command onto OS

            if (cmndbuf[0])
                system(cmndbuf);
        }
    }
}
return 0; 
}

【问题讨论】:

  • 你为什么要在 C 中这样做? (相对于,比如说,python)
  • 您希望有人重写您的程序吗?你看过 fork 和 exec 的手册吗?
  • 如果你使用任意系统命令,你必须使用system.一个 shell 语法解析器和实现大约有 20,000 行。

标签: c unix system exec fork


【解决方案1】:

我假设您有一个 POSIX 系统,例如 GNU/Linux。

这是一个很常见的问题。第一个答案是研究system 函数在GNU Libc 等免费C 库中的实现。也有很多关于 Unix 的好书涵盖了这个问题。

作为线索,systemfork-ing 一起工作,然后在 shell /bin/sh 的子进程 execve 中工作

【讨论】:

    【解决方案2】:

    Brian Kernighan 和 Rob Pike 的 The UNIX Programming Environment 中的“系统”函数实现示例。

    #include <signal.h>
    system(s) /* выполнить командную строку s */
    char *s;
    {
      int status, pid, w, tty;
      int (*istat)(), (*qstat)();
      extern char *progname;
      fflush(stdout);
      tty = open("/dev/tty", 2);
      if (tty == 1) {
        fprintf(stderr, "%s: can't open /dev/tty\n", progname);
        return 1;
      }
      if ((pid = fork()) == 0) {
        close(0); dup(tty);
        close(1); dup(tty);
        close(2); dup(tty);
        close(tty);
        execlp("sh", "sh", " c", s, (char *) 0);
        exit(127);
      }
      close(tty);
      istat = signal(SIGINT, SIG_IGN);
      qstat = signal(SIGQUIT, SIG_IGN);
    
      while ((w = wait(&status)) != pid && w != 1);
      if (w == 1)
        status = 1;
      signal(SIGINT, istat);
      signal(SIGQUIT, qstat);
      return status;
    }
    

    请注意,这本书是在 C 标准定稿之前编写的,所以它没有使用原型。

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 1970-01-01
      • 2012-02-02
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多