gpt4 book ai didi

c - 尝试通过 g_spawn_async 执行 shell 命令并读取输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:32 24 4
gpt4 key购买 nike

我正在尝试执行 shell 命令 (ls/home) 并尝试读取输出这个程序的问题到底在哪里?这是程序。

#include <stdio.h>
#include <glib.h>
#include <stdlib.h>
#include <signal.h>

typedef struct{
int std_in;
int std_out;
int std_err;
}child_fds;

gboolean cb_stdout(GIOChannel* channel, GIOCondition condition, gpointer data){
if(condition & G_IO_ERR ){
return TRUE;
}
if(condition & G_IO_HUP ){
return FALSE;
}
gsize actually_read;
gchar* shell_out = (gchar*)g_malloc0(512);
GIOStatus status = g_io_channel_read_chars(channel,shell_out, 512,&actually_read,NULL );
if(status != G_IO_STATUS_NORMAL){
//dont remove the source yet
g_free(shell_out);
return TRUE;
}
printf("%s \n",shell_out);
g_free(shell_out);
return TRUE;
}

GMainLoop * gml = NULL;

void sigterm_handler(int sig_num){
g_warning("signal recieved");
g_main_loop_quit(gml);
}

void child_handler(GPid pid, int status, gpointer data){
g_warning("child killer");
g_spawn_close_pid(pid);
}
int main(){
gml = g_main_loop_new(NULL, 0);
signal(SIGINT,&sigterm_handler ); //ctrl+c
gchar** command;
g_shell_parse_argv("/bin/ls /home",NULL, &command, NULL);
GPid ls_pid;
child_fds fds_ls;
if( g_spawn_async_with_pipes(NULL,
command,
NULL,
G_SPAWN_DO_NOT_REAP_CHILD,
NULL,
NULL,
&ls_pid,
&fds_ls.std_in,
&fds_ls.std_out,
&fds_ls.std_err,
NULL)
){
printf("succesfully spawned\n");
} else {
printf("spawning failed\n");
}
g_strfreev(command);
GIOChannel * std_out_ch = g_io_channel_unix_new(fds_ls.std_out);
g_io_add_watch(std_out_ch, G_IO_IN | G_IO_ERR | G_IO_HUP , (GIOFunc)cb_stdout , (gpointer)&fds_ls);
g_io_channel_unref(std_out_ch);
g_child_watch_add(ls_pid , (GChildWatchFunc)child_handler, NULL);
g_main_loop_run(gml);
return 0;
}

我不确定 io channel 的内存处理。也不确定主循环处理。也非常感谢您的建议。

最佳答案

乍一看,

if(condition | G_IO_ERR ){
return TRUE;
}
if(condition | G_IO_HUP ){
return FALSE;
}

似乎是错误的,因为两个条件的计算结果总是为真。您可能需要“&”运算符。

关于c - 尝试通过 g_spawn_async 执行 shell 命令并读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19606042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com