我尝试使用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
我应该进入目录吗?如果是的话,我该怎么办呢...
谢谢
答案 0 :(得分: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 */
}
(......其余的节目......)