How to execute a shell script from C in Linux?

后端 未结 6 1959
旧巷少年郎
旧巷少年郎 2020-11-28 03:34

How can I execute a shell script from C in Linux?

6条回答
  •  离开以前
    2020-11-28 04:08

    I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.

    Store you command in a char array parameters, and malloc space for the result.

    int fd[2];
    pipe(fd);
    if ( (childpid = fork() ) == -1){
       fprintf(stderr, "FORK failed");
       return 1;
    } else if( childpid == 0) {
       close(1);
       dup2(fd[1], 1);
       close(fd[0]);
       execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
    }
    wait(NULL);
    read(fd[0], result, RESULT_SIZE);
    printf("%s\n",result);
    

提交回复
热议问题