5

在这里我想执行一个命令,我必须在执行第一个命令后给这个命令输入。

我想obex_test为蓝牙模式执行命令,而不是在我必须提供像“s”这样的输入来启动服务器之后,所以我怎么能提供这个东西。这是我写这个东西并得到输出的代码。obex_test执行命令后出现输入数据错误。

代码:

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

void main() {

    char *input = "obex_test -b";   
    FILE *fp = NULL;
    char path[512];


    fp = popen(input, "w");

    if (fp == NULL) 
    {
        printf("\nFailed command\n");
        return;
    }
    else
    {
        printf("\nSuccesss command\n");
    }
    printf("starting while : %d", fp);

    while (fgets(path, sizeof(path) - 1, fp) != NULL) {

        printf("\nOutput    :::  %s \n", path);
    }

    printf("\nEnd\n");
    /* close */
    pclose(fp);

}

输出 :

Successs command
starting while : 69640
End
Using Bluetooth RFCOMM transport
OBEX Interactive test client/server.
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command
> Unknown command

在此行之后的输出中,OBEX Interactive test client/server.我必须提供输入字符's',但我无法直接执行此操作,它会进入无限循环和 printf >Unknown command

4

2 回答 2

3

哦,如果你想通过你的c文件给popen命令输入,那么试试这种方式

fputc ( 's', fp );
fputc ( '\n', fp);

在这里如果你想给 s 选项然后写's'

fp 是文件指针popen()

它工作正常

在您的代码中:

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

void main() {

    char *input = "obex_test -b";   
    FILE *fp = NULL;
    char path[512];


    fp = popen(input, "w");

    if (fp == NULL) 
    {
        printf("\nFailed command\n");
        return;
    }
    else
    {
        printf("\nSuccesss command\n");
    }

//giving s option to menu
fputc ( 's', fp );
fputc ( '\n', fp);



    printf("starting while : %d", fp);

    while (fgets(path, sizeof(path) - 1, fp) != NULL) {

        printf("\nOutput    :::  %s \n", path);
    }

    printf("\nEnd\n");
    /* close */
    pclose(fp);

}

编辑:克服无限循环

每次给出任何选项后都给出两个换行符

喜欢

//giving s option to menu
fputc ( 's', fp );
fputc ( '\n', fp);
fputc ( '\n', fp);
于 2012-01-27T06:13:31.170 回答
0

如果你想传递字符(stdin 选项),你可以使用 fputc 或者更好的是fputs

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

int main(int argc, char *argv[])
{
    FILE *fp = popen("/path/to/yourBinary cmdLineArgs", "w");

    if (fp == NULL)
    {
        printf("Failed to open the pipe\n");
    }
    else
    {
        // Option1: pass in character, by character
        fputc('n', fp);
        fputc('\n', fp);

        // Option2: provide 's' to the binary with the new line
        fputs("s\n", fp);

        // fputs allows multiple characters
        fputs("4096M\n", fp);

        pclose(fp);
    }

   return 0;
}
于 2018-03-08T14:27:27.610 回答