繁体   English   中英

如何在C中执行Shell脚本?

[英]How to execute a shell script in C?

我正在尝试创建.sh文件,将脚本写入其中,然后使用exec *执行

到目前为止,我设法创建了文件并向其中写入了代码,但是execl并未执行脚本

int main( int argc, char * argv[] ){
    char str[] = "#!/bin/bash \n echo 'Hello World!'";
    FILE *fp = fopen("script.sh", "w+");
    fwrite(str , 1 , sizeof(str) , fp );
    fclose(fp);
    execl ("/usr/bin/chmod", "chmod", "+x", "script.sh", (char *)0);
    execl ("/export/home/redpal/lab4", "script.sh", (char *)0);
    return 0;
}

我应该把每个execl放在子进程中吗?

execl函数(像所有exec(3)函数和execve(2)系统调用一样) 不会在成功时返回 它只会在失败时返回。

因此,您的第一个电话是:

execl ("/usr/bin/chmod", "chmod", "+x", "script.sh", (char *)0);

很可能成功。 然后,您当前的程序消失了,您的进程正在运行/usr/bin/chmod程序。 该程序完成后(几毫秒内),您的进程将退出(调用外壳程序将给出新的提示)。

您应该考虑使用chmod(2)系统调用,而不是使用/usr/bin/chmod 程序

程序的其余部分也是错误的。 您可能要exec生成的脚本(但是,然后,需要给出其完整路径)。

您需要了解如何使用fork(2)execve(2)waitpid(2)和朋友系统调用来运行进程。 我们无法解释如何做到这一点(太长了),但是您应该阅读《 高级Linux编程》这本书的几章(可免费下载)。

也许您应该考虑在实际程序中嵌入LuaGuile之类的解释器(因此您的问题看起来像是XY问题

您可能只使用system(3)popen(3)运行某些命令。...也许使用诸如FILE* cmd = popen("/bin/sh", "w"); 可能就足够了。...然后将shell命令写入cmd然后需要pclose(cmd)

在每个可能失败的命令之后检查错误。 您应该将sizeof(array)-1个字节写入文件,或者还要写入终止的零。

exec* syscalls替换过程映像。 如果它们成功,则您的程序将替换为您刚刚执行的二进制文件。 因此,您要么需要在子进程中执行,要么exec* syscall是您在程序中要做的最后一件事。

在您的情况下,完全可以避免执行chmod 您可以直接发出chmod syscall,也可以确保创建文件,在这种情况下,可以立即设置权限。

我想要这样:

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

int main( int argc, char * argv[] )
{
    unlink("script.sh"); //unchecked -- let it fail if the file's not there
    int fd;
    if(0>(fd = open("script.sh", O_CREAT|O_WRONLY, 0777)))
        { perror("Couldn't create 'script.sh'"); return EXIT_FAILURE; }
    int nr;
    static char const str[] = "#!/bin/bash \n echo 'Hello World!'";
    size_t to_write = sizeof str - 1;
    if( to_write != (nr=write(fd, str, sizeof str - 1)) || 0>close(fd)  )
        { perror("Couldn't write contents"); return EXIT_FAILURE; }
    //writes to the filesystem on linux aren't ever partial unless there's a filesystem error 
    //otherwise you need to account for partial write (which fwrite does for you)

    execl ("./script.sh", "script.sh", (char *)0);
    perror("Couldn't exec './script.sh'");
    return EXIT_FAILURE;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM