문제

Linux CLI 명령을 실행하고 C에서 stdout 출력을 가져와야합니다.

파이프 ()를 사용하여 파이프를 만들고 포크/exec, exec ()을 호출하기 전에 어린이의 stdout 디스크립터를 파이프로 리디렉션하고 부모의 파이프에서 읽을 수 있습니다. 게다가 아이를 기다려야 할 것입니다.

System ()가 포크 + exec + 대기를하는 것처럼 포크 + 리디렉션 + exec + 대기를하는 간단한 호출이 있습니까? System () 만 리디렉션을 수행하지 않습니다.

Fork + Redirect + Exec를 수행하는 Popen ()이 있지만 기다리지 않으므로 종료 상태를 얻을 수 없습니다.

도움이 되었습니까?

해결책

이게?

NAME
       popen, pclose - process I/O

SYNOPSIS
       #include <stdio.h>  

       FILE *popen(const char *command, const char *type);

       int pclose(FILE *stream);

DESCRIPTION
       The  popen()  function opens a process by creating a pipe, forking, 
and invoking the shell.  Since a pipe is by definition unidirectional, the 
type argument may specify only reading or writing, not both; the resulting 
stream is correspondingly read-only or write-only.

       The command argument is a pointer to a null-terminated string 
containing a shell command line.  This command is passed to /bin/sh 
using the -c flag; interpretation, if any, is performed by the shell.  
The type argument is a pointer to a null-terminated string which must be 
either ‘r’ for reading or ‘w’ for writing.

       The  return  value  from popen() is a normal standard I/O stream in 
all respects save that it must be closed with pclose() rather than fclose().  
Writing to such a stream writes to the standard input of the command; the 
command’s standard output is the same as that of the process that called 
popen(), unless this is altered by the command itself.  Conversely, reading 
from a ‘‘popened’’ stream reads the command’s standard output, and the 
command’s standard input is the same as that of the process that called 
popen().

       Note that output popen() streams are fully buffered by default.

       The pclose() function waits for the associated process to terminate 
and returns the exit status of the command as returned by wait4().

다른 팁

glib은 이것에 대한 좋은 기능을 가지고 있습니다. g_spawn_sync(): http://library.gnome.org/devel/glib/stable/glib-spawning-processes.html#g-spawn-sync

예를 들어, 명령을 실행하고 종료 상태 및 출력을 얻으려면 다음과 같습니다.

const char *argv[] = { "your_command", NULL };
char *output = NULL; // will contain command output
GError *error = NULL;
int exit_status = 0;
if (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL, 
                  &output, NULL, &exit_status, &error))
{
  // handle error here
}

사용 popen() 그리고 pclose().


popen() 물론 실제로 대기하지 않지만 파이프의 읽기는 데이터가 사용될 때까지 차단됩니다.

pclose() 대기하지만, 조기에 부르는 것은 포크 프로세스에서 약간의 출력을 차단할 수 있습니다. 아이가 끝나면 스트림에서 결정하고 싶을 것입니다 ...


아마도 이미 논의 될 수 있습니다 C에서 외부 프로그램을 실행하고 출력을 구문 분석하려면 어떻게해야합니까?

여기에 내가 사용하는 것은 다음과 같습니다.

   /* simply invoke a app, pipe output*/
    pipe = popen(buf, "r" );
    if (pipe == NULL ) {
        printf("invoking %s failed: %s\n", buf, strerror(errno));
        return 1;
    }

    waitfor(10);

    while(!feof(pipe) ) {
        if( fgets( buf, 128, pipe ) != NULL ) {
            printf("%s\n", buf );
        }
    }

    /* Close pipe */
    rc = pclose(pipe);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top