c/popen 中的 bash 找不到我的脚本

问题描述 投票:0回答:2

我尝试使用 popen 从 C 程序执行我的 bash 脚本 (

tes02.sh
)。但是当我运行我的程序时,我收到消息:
./tes02.sh: not found
这是程序:

 #include <stdio.h>

#define LINE_BUFSIZE 128

int main(int argc, char *argv[])
{
    char line[LINE_BUFSIZE];
    int linenr;
    FILE *pipe;

    /* Get a pipe where the output from the scripts comes in */
    pipe = popen("./tes02.sh", "r");
    if (pipe == NULL) {  /* check for errors */
        perror(argv[0]); /* report error message */
        return 1;        /* return with exit code indicating error */
    }

    /* Read script output from the pipe line by line */
    linenr = 1;
    while (fgets(line, LINE_BUFSIZE, pipe) != NULL) {
        printf("Script output line %d: %s", linenr, line);
        ++linenr;
    }

    /* Once here, out of the loop, the script has ended. */
    pclose(pipe); /* Close the pipe */
    return 0;     /* return with exit code indicating success. */
}

我的脚本目录是:

/home/pi
我应该进入目录吗?如果是的话,请问我该怎么做... 谢谢你

c bash popen raspbian
2个回答
0
投票

我会首先检查该文件是否存在于您当前的目录中:

if ( 0 != access( "./tes02.sh", F_OK ) )
{ 
    fprintf ( stderr, "File tes02.sh does NOT exist in curdir\n" );
    return -1; // return code - normally I return negative codes for errors
}
/* Get a pipe where the output from the scripts comes in */
pipe = popen("./tes02.sh", "r");
if (pipe == NULL) {  /* check for errors */
    perror(argv[0]); /* report error message */
    return 1;        /* return with exit code indicating error */
}

(...节目的其余部分...)


0
投票

您还应该确保您的脚本以像

#!/bin/bash

这样的 shebang 开头 这允许 shell 调用解释器。

如果您无法更改脚本,您可以尝试调用 /bin/bash 并将脚本作为参数传递。

© www.soinside.com 2019 - 2024. All rights reserved.