weixin_40001417 2017-10-13 11:29 采纳率: 100%
浏览 794
已采纳

C语言编程问题求帮助帮忙

图片说明
linux系统txt文本里有几行指令,我想把他们存到char指针数组然后fork用execvp去执行这些指令,想一次性把图片里的三个指令运行了,希望好心人帮忙解决问题。

  • 写回答

1条回答 默认 最新

  • bear_priestess 2017-10-14 12:54
    关注

    /*-----------------------------------------------------------------*/
    /* This file is modified based on /
    /
    http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/shell.c /
    /
    Enjoy your learning. Good luck. /

    /
    -----------------------------------------------------------------*/

    #include
    #include
    #include

    void parse(char line, char **argv)
    {
    while (*line != '\0') { /
    if not the end of line ....... /
    while (*line == ' ' || *line == '\t' || *line == '\n')
    *line++ = '\0'; /
    replace white spaces with 0 /
    *argv++ = line; /
    save the argument position /
    while (*line != '\0' && *line != ' ' &&
    *line != '\t' && *line != '\n')
    line++; /
    skip the argument until ... /
    }
    *argv = '\0'; /
    mark the end of argument list */
    }

    void execute(char **argv)
    {
    pid_t pid;
    int status;

     if ((pid = fork()) < 0) {     /* fork a child process           */
          printf("*** ERROR: forking child process failed\n");
          exit(1);
     }
     else if (pid == 0) {          /* for the child process:         */
          if (execvp(*argv, argv) < 0) {     /* execute the command  */
               printf("*** ERROR: exec failed\n");
               exit(1);
          }
     }
     else {                                  /* for the parent:      */
          while (wait(&status) != pid);       /* wait for completion  */
    

    ;
    }
    }

    void main(void)
    {
    char *argv[60];
    FILE *fp;
    fp = fopen("a.txt","r");
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    while ((read = getline(&line, &len, fp)) != -1)
    {
    printf("bash: %s", line);
    line[read -1]='\0';
    parse(line, argv);
    execute(argv);
    }

    }

    
    

    写了指令的文件放在同一目录下

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题