g_spawn_async_与管道()和bash
我正在用glibwithbash中的管道()测试g_spawn_async_ 我想知道是否可以将此函数作为子进程启动bash,将命令从父进程写入子进程(bash)输入,并从bash输出中获得结果 我的c程序应该充当交互式shell的接口 我认为我没有给bash提供好的选项,我也不太理解bash是如何工作的(我在手册页中看到,在交互模式下,bash的输出、输入链接到tty/终端) 我已经测试了很多东西,下面是一些代码:g_spawn_async_与管道()和bash,bash,glib,Bash,Glib,我正在用glibwithbash中的管道()测试g_spawn_async_ 我想知道是否可以将此函数作为子进程启动bash,将命令从父进程写入子进程(bash)输入,并从bash输出中获得结果 我的c程序应该充当交互式shell的接口 我认为我没有给bash提供好的选项,我也不太理解bash是如何工作的(我在手册页中看到,在交互模式下,bash的输出、输入链接到tty/终端) 我已经测试了很多东西,下面是一些代码: //launcher: GPid pid; gchar
//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 );
}
尝试使用
-i
运行bash
,并关注3个IOs:fd/0
->stdin、fd/1
->stdout和fd/2
->stderr
。。。看看
manbash
,搜索interactive.你的意思是我应该用/proc/bash\u-pid/fd0编写,并在/proc/bash\u-pid/fd1和proc/bash\u-pid/fd2上添加我的观察程序。如果你的C
程序必须是bash包装器,那么在将进程转移到bash时,你必须打开并使用3个文件描述符(-I
)。不幸的是,我不是C
程序员,所以我无法编写open
命令示例。感谢您的帮助。不幸的是,/proc/bash_pid/fd/x似乎只有在以非交互模式启动bash时才有用。正如我在前面的问题中提到的,当以交互模式启动时,输出/错误被重定向到tty。我能找到的唯一方法是在新的bash中使用forkpty和write/read。下面是一个我觉得有趣的示例链接(即使我只想编写一个使用bash而不是一些shell mitm的程序):