0

我正在使用 bash 测试 glib 中的 g_spawn_async_with_pipes ()。

我想知道是否可以使用此函数作为子进程启动 bash,将命令从父进程写入子进程(bash)输入并从 bash 输出中获取结果?

我的 c 程序应该充当交互式 shell 的接口。

我认为我没有为 bash 提供好的选择,而且我并不真正了解 bash 的工作原理(我在手册页中看到在交互模式下 bash 的输出、输入链接到 tty/终端)。

我已经测试了很多东西,这里有一些代码:

//launcher:
GPid        pid;
gchar      *launch[] = {"/bin/bash","-s",NULL };
gint        in,
            out,
            err;
GIOChannel *out_ch,
           *err_ch;
gboolean    ret;

/* Spawn child process */
ret = g_spawn_async_with_pipes( NULL, launch, NULL,
                                G_SPAWN_DO_NOT_REAP_CHILD | 
                                G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
                                NULL, &pid, &in, &out, &err, NULL );
if( ! ret )
{
    g_error( "SPAWN FAILED" );
    return;
}

/* Create channels that will be used to read data from pipes. */
out_ch = g_io_channel_unix_new( out );
err_ch = g_io_channel_unix_new( err );

/* Add watches to channels */
g_io_add_watch( out_ch, G_IO_IN | G_IO_HUP, (GIOFunc)cb_out_watch, NULL );
g_io_add_watch( err_ch, G_IO_IN | G_IO_HUP, (GIOFunc)cb_err_watch, NULL );

//create channel for input:
GIOChannel * input_channel;
input_channel = g_io_channel_unix_new (in);

//create the string "date\r\n" to send to bash input
GString * cmd = g_string_new("date");
GString * carriage_return = g_string_new("\r\n");
g_string_append(cmd,carriage_return->str);
GError * error;
error = NULL;
gsize bytes_written;
printf("Launching date in bash:\n");
g_io_channel_write_chars( input_channel,
                          cmd->str,
                          cmd->len,
                          &bytes_written,
                          &error);
if (error != NULL)
{
  printf("%s\n", error->message);
}

这是 cb_out_watch 的代码

static gboolean
cb_out_watch( GIOChannel   *channel, GIOCondition  cond, gpointer user_data )
{
    printf("->reading bash output\n");
    gchar *string;
    gsize  size;

if( cond == G_IO_HUP )
{
    g_io_channel_unref( channel );
    return( FALSE );
}

g_io_channel_read_line( channel, &string, &size, NULL, NULL );
printf("output : \n:%s\n", string);
g_free( string );

return( TRUE );
}
4

1 回答 1

0

尝试运行bash-i关心3 个 IOfd/0-> stdinfd/1-> stdoutfd/2-> stderr

... ...并看看man bash,寻找互动

于 2012-12-18T20:20:51.330 回答