简体   繁体   English

捕获程序C中的Shell脚本输出

[英]Catching shell script output in program c

I have C program ( program.c ) that calls a shell script ( command.sh ). 我有C程序(program.c),它调用外壳程序脚本(command.sh)。 command.sh returns an output (a password), i need to get this output in my program.c. command.sh返回输出(密码),我需要在我的program.c中获取此输出。 using system(command); 使用system(command); , i can't get hold of the output. ,我无法掌握输出。 is there any other way in C to solve my problem? C中还有其他方法可以解决我的问题吗?

Not in pure C. You want POSIX. 不是纯C语言。您需要POSIX。 Specifically popen function. 特别是popen函数。

The specification has a nice example, that you can just copy 1:1 http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html 该规范有一个很好的例子,您可以只复制1:1 http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html

Sounds like you're afraid to use libraries. 听起来好像您害怕使用库。 Please try and use libraries, they're just as much part of Unix as shell tools. 请尝试使用库,它们与Shell工具一样在Unix中一样重要。

In pure C (well ... ignoring the contents of the system() call) you can redirect the shell script output to a file, then read that file. 在纯C语言中(好吧...忽略system()调用的内容),您可以将Shell脚本输出重定向到一个文件,然后读取该文件。

system("whatever > file");
handle = fopen("file", "r");
/* if ok use handle */
fclose(handle);

You should open a pipe using popen but this sounds tedious. 您应该使用popen打开管道,但这听起来很乏味。 AC program calling a shell script for a password. 调用shell脚本输入密码的AC程序。

You can use popen() as suggested above, but note that in this case you have no control over the process you created (eg you will not be able to kill it), you also will not know its exit status. 您可以按照上面的建议使用popen() ,但请注意,在这种情况下,您无法控制创建的进程(例如,您将无法杀死它),您也将不知道其退出状态。

I suggest using classical pipe/fork/exec combination. 我建议使用经典的pipe / fork / exec组合。 Then you will know the pid of your child process, so you will be able so send signals, also with pipe() you are able to redirect process standard output, so you can easily read it in your parent process. 然后,您将知道子进程的pid,这样便可以发送信号,还可以使用pipe()重定向进程标准输出,以便可以在父进程中轻松读取它。 As example you can see my accepted answer to popen() alternative . 例如,您可以看到我接受的popen()替代答案。

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

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