trying to execute shell command by g_spawn_async and read the output

…衆ロ難τιáo~ 提交于 2019-12-13 00:46:08

问题


I was trying to execute a shell command (ls /home) and trying to read the output where actually is the problem with this program? Here is the program.

#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;
}

I am not sure about the memory handling with io channels. Also not sure about the mainloop handling. Suggestions are also greatly appreciated.


回答1:


On first glance, the

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

seem to be wrong because both conditions evaluate always to true. You probably want the `&' operator.



来源:https://stackoverflow.com/questions/19606042/trying-to-execute-shell-command-by-g-spawn-async-and-read-the-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!