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

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

    }

    
    

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

    点赞 打赏 评论

相关推荐 更多相似问题